寫在前面
由於之前都是采用托控件的方式進行界面的編輯,覺得自己對於UI編程的領悟還是那么的有欠缺,所以現在自己想通過代碼的形式進行界面的編輯。
問題以及解決思路
新建一個QT工程,在MainWindow的構造函數寫下如下代碼后,界面仍是一片空白。
QPushButton* button_1 = new QPushButton("one"); QPushButton* button_2 = new QPushButton("two"); QPushButton* button_3 = new QPushButton("three"); QHBoxLayout* hLayout = new QHBoxLayout(); //QVBoxLayout* vLayout = new QVBoxLayout(); hLayout->addWidget(button_1); hLayout->addWidget(button_2); hLayout->addWidget(button_3); this->setLayout(hLayout);
控件到哪里去了?原來在QT里面,控件的顯示是通過QWidget來進行顯示的,QMainWindow不算是QWidget,所以這樣無法顯示。為了解決這個問題,就可以在代碼中這么解決:
QWidget* w = new QWidget(); this->setCentralWidget(w); QPushButton* button_1 = new QPushButton("one"); QPushButton* button_2 = new QPushButton("two"); QPushButton* button_3 = new QPushButton("three"); QHBoxLayout* hLayout = new QHBoxLayout(); //QVBoxLayout* vLayout = new QVBoxLayout(); hLayout->addWidget(button_1); hLayout->addWidget(button_2); hLayout->addWidget(button_3); w->setLayout(hLayout);
細心的讀者看到了這兩段代碼的區別了嗎?沒錯,這就是解決方案。
如果我們新建的工程是QWidget會不會也出現這個問題呢?繼續探討:
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QPushButton* button_1 = new QPushButton("one"); QPushButton* button_2 = new QPushButton("two"); QPushButton* button_3 = new QPushButton("three"); QHBoxLayout* hLayout = new QHBoxLayout(); //QVBoxLayout* vLayout = new QVBoxLayout(); hLayout->addWidget(button_1); hLayout->addWidget(button_2); hLayout->addWidget(button_3); this->setLayout(hLayout); }
結果如下:
正如我們預期的那樣,所以可以得出這么一個結論,在QT里面的所有的控件均是通過QWidget來進行顯示的。