Accessing Qt Layout created in UI from code?

后端 未结 1 1900
野性不改
野性不改 2021-02-07 02:54

This is probably the dumbest problem I have ever had, but I am extremely confused. I am trying to get started with layouts, but for some reason cannot figure this one out.

1条回答
  •  甜味超标
    2021-02-07 03:42

    Assuming, you have simply set a QGridLayout in QtDesigner to your centralWidget in the MainWindow like this:

    enter image description here

    you can access it in your MainWindow code in that way with the correct object name (here it is gridLayout):

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->gridLayout->addWidget(new QLabel("hello world"),0,0);
    }
    

    If you have set a layout in QtDesigner or in code and you want to change the layout, QWidget won't let you install another one and you will get an error message like this:

    QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which already has a layout

    In this case you have to delete the existing layout at first and then install the new one like in your code above.

    If you want to access the layout in your main function you can achieve this by the QObject::findChild function like this:

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
    
        QGridLayout *gridLayout = w.findChild("gridLayout");
        Q_ASSERT(gridLayout);
        gridLayout->addWidget(new QLabel("hello, the second"));
    
        w.show();
        return a.exec();
    }
    

    0 讨论(0)
提交回复
热议问题