Home > Mobile >  Is it OK to share a QLineEdit between Layouts?
Is it OK to share a QLineEdit between Layouts?

Time:03-30

I'm debugging some code that uses the same QLineEdit between two layout boxes. Is this legal? It looks like the 2nd layout box is grabbing control, and they don't render in the first layout.

But I can't find any documentation to say whether this is a valid use-case, and (perhaps) something else is wrong.

Pseudocode:

QLineEdit *valueEdit = new QLineEdit();

[...]

QGridLayout *layout1 =  new QGridLayout();
QGridLayout *layout2 =  new QGridLayout();

[...]

layout1->addWidget( valueEdit, 0, 0, Qt::AlignLeft );
layout2->addWidget( valueEdit, 0, 0, Qt::AlignLeft );  // same edit, 2x layouts, possible?

I suspect the code is trying to re-use the edit field, so it only needs to read update values from one set of widgets. (But I'm only guessing.) During execution, only ever one of the layouts is visible at a time.

CodePudding user response:

It's safe to do, but it won't result in the QLineEdit appearing in both locations. If you look in the QLayout::addChildWidget(QWidget * w) method of qlayout.cpp, you'll see this code:

void QLayout::addChildWidget(QWidget *w)
{
    QWidget *mw = parentWidget();
    QWidget *pw = w->parentWidget();

    if (pw && w->testAttribute(Qt::WA_LaidOut)) {
        QLayout *l = pw->layout();
        if (l && removeWidgetRecursively(l, w)) {
#ifdef QT_DEBUG
            if (Q_UNLIKELY(layoutDebug()))
                qWarning("QLayout::addChildWidget: %s \"%ls\" is already in a layout; moved to new layout",
                         w->metaObject()->className(), qUtf16Printable(w->objectName()));
#endif
        }
    }
    if (pw && mw && pw != mw) {
#ifdef QT_DEBUG
            if (Q_UNLIKELY(layoutDebug()))
                qWarning("QLayout::addChildWidget: %s \"%ls\" in wrong parent; moved to correct parent",
                         w->metaObject()->className(), qUtf16Printable(w->objectName()));
#endif
        pw = nullptr;
    }

As the debug messages indicate, on the second call to addWidget(), the widget will be moved out of its old parent-widget and layout and into the new one.

  • Related