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

今天QT写程序时,发现了一个问题,就是我在一个窗口中放置了几个按钮,可是那几个按钮在最后在显示图形中始终无法出现,具体实现代码如下:

MainWindow::MainWindow(QWidget *parent)

    : QMainWindow(parent)
{
    a = new QPushButton(tr("123"));
    b = new QPushButton(tr("456"));
    c = new QPushButton(tr("789"));
    layout = new QVBoxLayout(this);
    layout->addWidget(a);
    layout->addWidget(b);
    layout->addWidget(c);
   
}

经过一番查阅之后,发现原来是因为窗口继承的是QMainwindow,所以需要设置 setCentralWidget();即把代码改成如下即可:

MainWindow::MainWindow(QWidget *parent)

    : QMainWindow(parent)
{
    a = new QPushButton(tr("123"));
    b = new QPushButton(tr("456"));
    c = new QPushButton(tr("789"));
    layout = new QVBoxLayout();
    layout->addWidget(a);
    layout->addWidget(b);
    layout->addWidget(c);
 
 QWidget * widget = new QWidget (this) ;
    widget->setLayout(layout) ;
    this->setCentralWidget(widget) ;
}

你可能感兴趣的:(Web,qt,布局,图形,widget)