相信大家都碰見過這種情況,新建的工程窗體選的是QMainWindow。界面佈局不是直接託控件,直接在代碼中new出控件對象,然後添加到layout中了,最後在在 setLayout的時候,發現界面顯示的效果和預期不一樣,
在QDialog的派生類中,添加Layout,可在創建Layout對象的同時指定其父窗口;
但這在QMainWindow中行不通。
基於主窗口的程序,默認已經有了自己的佈局管理器。
QMainWindow的中心控件是一個QWidget,可以通過setCentralWidget設置。
若想在QMainWindow中添加 layout,需要通過將該Layout添加到一個QWidget對象中,
然後將該佈局設置爲該空間的佈局,最後設置該控件爲QMainWindow的中心控件,代碼如下:
m_widget_search_filter = new SearchFilter(); //文件瀏覽
m_widget_image_viewr = new ImageViewer(); //圖片瀏覽
QHBoxLayout* main_layout = new QHBoxLayout();
main_layout->addWidget(m_widget_search_filter);
main_layout->addWidget(m_widget_image_viewr);
QWidget* main_widget = new QWidget(this);
main_widget->setLayout(main_layout);
this->setCentralWidget(main_widget);