在QMainWindow添加控件,无法显示问题

时间:2024-04-17 14:17:21
原文:http://blog.chinaunix.net/uid-25147458-id-3325066.html
 
 
今天在QMainWindow添加控制,无法显示,加上布局管理器后也一样,到底为何?
      首先,对于QDialog而言,添加控件过程:
      1、创建子窗口部件,如
           QRadioButton *radio1 = new QRadioButton(tr("&Radio button 1"));
       2、创建一个布局
            QVBoxLayout *vbox = new QVBoxLayout;
       3、将子窗口部件添加到布局中去
            vbox->addWidget(radio1);
        4、将布局设置到QDialog中去
             this->setLayout(vbox);
        这样,在Qdialog就可以看到子窗口部件了;但在QMainWindow中看不到???
       求助google、百度,从QT Assistant 中找到这句话:
Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.
      原来mainwindow必须要有个centralWidget.于是便给他一个widget。示例代码如下:

    QWidget *centerWindow = new QWidget;
    this->setCentralWidget(centerWindow);
    
    button1 = new QPushButton("One");
    button2 = new QPushButton("Two");
    button3 = new QPushButton("Three");
    button4 = new QPushButton("Four");
    button5 = new QPushButton("Five");
    layout = new QVBoxLayout;
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    layout->addWidget(button4);
    layout->addWidget(button5);
    QGroupBox *groupBox = new QGroupBox(tr("登录"));
    groupBox->setLayout(layout);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(groupBox);
    
    centerWindow->setLayout(mainLayout);