Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing QWidgets

Tags:

c++

qt

How can I compare QWidgets? Lets say I have a list and would like to change the sizes of Widgets which are only QPushButton:

For example, is there any function or method to do this?

QList<QLayoutItem *> itemList;

if(itemList->Items->type() == QPushButton)
{
  item.setGeometry(newRect);
}
like image 265
kemal fahri Avatar asked Feb 15 '23 20:02

kemal fahri


1 Answers

There are several ways to do this, actually. QObject::inherits() is one:

for (int i = 0; i < itemList.size(); ++i) {
    if (itemList[i]->inherits("QPushButton")) {
        itemList[i]->setGeometry(newRect);
    }
}

Another way is using qobject_cast, which is what I recommend. It returns a null pointer if the object does not inherit (directly or not) from the class you cast to:

for (int i = 0; i < itemList.size(); ++i) {
    if (qobject_cast<QPushButton*>(itemList[i])) {
        itemList[i]->setGeometry(newRect);
    }
}

Note that qobject_cast does not need RTTI support to be enabled in the compiler.

And there's of course the standard C++ dynamic_cast which does need RTTI support enabled:

for (int i = 0; i < itemList.size(); ++i) {
    if (dynamic_cast<QPushButton*>(itemList[i])) {
        itemList[i]->setGeometry(newRect);
    }
}

Another method that would appear OK at first glance, but ultimately should not be used in this case, is QMetaObject::className(). Do not use this, because you'll get false negatives with QPushButton subclasses.

The reason I recommend qobject_cast is because it allows the compiler to check the typename. This is important when changing the name of a class. The compiler isn't able to check that when using the string-based QObject::inherits() function, so the code will continue to compile without problems but it won't work at runtime.

like image 128
Nikos C. Avatar answered Feb 18 '23 10:02

Nikos C.