How to add buttons to a main window in Qt?

后端 未结 1 1155
Happy的楠姐
Happy的楠姐 2020-12-28 20:33

I\'m new to qt programming so please don\'t mind if you find it a noob question. I\'ve added a button to my main window but when I run the code the button is not displayed.

1条回答
  •  萌比男神i
    2020-12-28 20:56

    In main window you should use central widget . You have two choices :

    Set the button for central widget ( Not so good choice ) :

    QPushButton *train_button = new QPushButton(this);
    train_button->setText(tr("something"));
    setCentralWidget(train_button);
    

    Add a widget and add the button to that widget and set the widget for centralWidget :

    QWidget * wdg = new QWidget(this);
    QPushButton *train_button = new QPushButton(wdg);
    train_button->setText(tr("something"));
    setCentralWidget(wdg);
    

    And surely you can use Layouts for your centralWidget:

    QWidget * wdg = new QWidget(this);
    QVBoxLayout *vlay = new QVBoxLayout(wdg);
    QPushButton *btn1 = new QPushButton("btn1");
    vlay->addWidget(btn1);
    QPushButton *btn2 = new QPushButton("btn2");
    vlay->addWidget(btn2);
    QPushButton *btn3 = new QPushButton("btn3");
    vlay->addWidget(btn3);
    wdg->setLayout(vlay);
    setCentralWidget(wdg);
    

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