groenhen groenhen - 1 year ago 47
C++ Question

Qt/C++ : Is "static_cast" ok for casting in this snippet of code?

I am using Qt5 on Windows 7. In my current app I have the following piece of code that changes the background color of some push-buttons:

for(int i = 0; i < layout()->count(); i++)
QPushButton * button = static_cast<QPushButton*>(layout()->itemAt(i)->widget());

Well, I have 2 questions about the above code:

  1. Is it ok/correct to use
    or should I use some other type of casting?

  2. Is it possible to use
    instead of the
    for loop

Answer Source

You should use qobject_cast so you can check if the cast was successful. It returns 0 if the cast failed.

QPushButton * button = qobject_cast<QPushButton*>(layout()->itemAt(i)->widget());
    // cast ok
    // cast failed

You can't use foreach as you would need a container for that.