6

I want to disable all but a selected set of widgets in my Qt application.

What I am trying to do is to iterate all children of mainWindow using findChildren and disable all the resulting widgets except 'myTable' using setEnabled(false).

QList<QWidget *> allWidgets = mainWindow->findChildren<QWidget *>("");
QList<QWidget*>::iterator it;
for (it = allWidgets.begin(); it != allWidgets.end(); it++) {
    if ((*it)->objectName() != "myTable")  // here, objectName is not working!!
    {
        (*it)->setEnabled(false);
    } 
}

objectName() inside the above if statement is not working. What do I put there?

László Papp
  • 51,870
  • 39
  • 111
  • 135
fortytwo
  • 491
  • 1
  • 5
  • 16

3 Answers3

6

The objectName function does not return the class name or the variable name, but the actual object name you have set with QObject::setObjectName. Therefore you first need to set it in your table with:

myTable->setObjectName("myTable");
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • As **SingerOfTheFall** suggested, disabling all widgets and enabling the one I want was easier in my case. But thank you. – fortytwo Nov 26 '13 at 06:31
2

You could use the accessibleName property. Set it for the widget you need, and then check it in your cycle with acessibleName() function. It is an empty string by default, so it should be fairly easy to find your widget.

Another alternative is to disable all widgets, and then just enable the one you need directly:

for( QWidget * w : widgets )
{
    w->setEnabled(false);
}

ui->myTable->setEnabled(true);

Or, finally, you can set the objectName property with the setObjectName() function, and use it as you do in your code.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • Thank you. I actually went about disabling all widgets and enabling the one I want. – fortytwo Nov 26 '13 at 06:28
  • Please use foreach in a Qt code rather than C++11 only features. That is why foreach is still kept around because Qt has to work with pre-c++11 compilers at this point of time. – László Papp Dec 26 '13 at 11:28
  • @lpapp I hugely doubt C++ keeps `foreach` around just for the sake of one 3rd-party library. Users can program in whichever dialect of C++ they want; they aren't mandated to support pre-11 compilers. Besides, even in 2012, before you posted, Qt was using C++11 features _within itself_: http://woboq.com/blog/cpp11-in-qt5.html. I suggest you stop reeling off your own coding opinions as if they were facts everyone else has to obey. – underscore_d Dec 11 '15 at 18:10
2

Write this on the first row (remove the quotation marks from the brackets):

QList<QWidget *> allWidgets = mainWindow->findChildren<QWidget *>();