Important: Please read the Qt Code of Conduct -

FindChildren returning too many objects

  • I have widgets of type QWidget, QTextEdit and QLineEdit stacking on each other in some random non-relevant layout all of which are children of the QWidget we can call 'activeFile'. I also have a declared QObject* co ... this is my casted object for the comparison under here. ct and cw are declared in the header as QTextEdit* ct; and QWidget* cw;.

    I am cycling the children of the widget as so:

    QList<QWidget *> widgets = activeFile->findChildren<QWidget *>();
    foreach(QWidget *cycledWidget, widgets) {
    qDebug() << "a child of the active file was found";
    co = cycledWidget;
    if (ct = qobject_cast<QTextEdit *>(co)) {
    			qDebug() << "TextEdit found";
    } else if (cw = qobject_cast<QWidget *>(co)) {
    			qDebug() << "Widget found";

    which works fine EXCEPT it gives me the debug alert many many many times saying "a child of the active file was found" without telling me which widget was "found", meaning it isnt either of these widgets? With more child widgets this is starting to take A LOT of time to search through these children all in which the program is unresponsive.

    I ran the code with only one child, all worked perfectly in finding the child and identifying it by its correct type, that is all EXCEPT QTextEdit with consistently gave 5 undefined objects.

    I also can't explain why having more children results in this problem becoming much bigger having around 50 widgets takes about 10 minutes to cycle through with this code and gives many hundred times the debug message "a child of the active file was found", far more than the actual count of widgets.

    I'm accessing data members in this loop by the way which also works but my problem here is the speed is unbelievably slow and I cannot figure out why I am getting so many undefinable objects. Can someone offer me some guidance or correct my above code? All my widgets have objectnames so I wasnt able to put the double double quotes in the brackets for the find children parameter.

  • Hi CoreySean, what happens if you apply the qobject_cast directly on cycledWidget instead of using the co?

  • @stryga42 works perfect, i overlooked that and am very appreciative of the extra set of eyes! Thank you kindly.

    The QTextEdit still gives its 5 unidentified objects but its the only one now, i was getting A LOT more before but I replicated the same conditions and only have these 5

  • Lifetime Qt Champion


    Out of curiosity, why do you need to use findChildren within your widget ?

Log in to reply