簡單說下 想要實現的內容
我們有一個主窗口mainwindow,需要向其中放入新的界面,你可以自己定義里面內容。
大致的效果圖如下

實現起來就是利用QT的layout布局 使用水平布局QHboxlayout或QVboxLayout
第一步,先進入ui編輯界面,加入一個水平或者垂直的布局(根據自己選則,我用水平)充滿整個mainwindow

注意右邊我更改了 QHBoxLayout的名稱 為pHBoxLayout
然后運行一遍 ;(注意需要運行一遍 要不然類找不到pHBoxLayout 這個布局)
接着定義一個方法(向mainwindow增加窗口的方法) (mainwindow.cpp)
1 void MainWindow::putwidget(QWidget* widget) 2 { 3 ui->pHBoxLayout->addWidget(widget); 4 }
新建一個class文件 定義為myWidget名稱 inherent QObject和QWidget
在類名myWidget后面增加 :public QWidget

在myWidget中增加該窗口的背景色 區分其他區域
1 myWidget::myWidget() 2 { 3 this->setAttribute(Qt::WA_StyledBackground,true); 4 this->setStyleSheet("background-color: rgb(255,255, 255)"); 5 }
在main函數中添加(main.cpp)
myWidget *widget=new myWidget(); w.putwidget(widget);
編譯運行一下
得到如下結果

后面的工作比較重復 就是慢慢增加左右布局,再將布局添加控件
注意兩點:
新建一個layout布局時需要指定父類在括號中 leftWidget為需要定義布局的控件
1 QVBoxLayout *PHVBoxLayout=new QVBoxLayout(leftWidget);
定義這個控件時,需要定義指針形式
mywidget文件的代碼為
#include "myWidget.h" #include <QHBoxLayout> #include <QVBoxLayout> myWidget::myWidget() { this->setAttribute(Qt::WA_StyledBackground,true); this->setStyleSheet("background-color: rgb(255,255, 255)"); QWidget *leftWidget=new QWidget(); leftWidget->setStyleSheet("background-color: rgb(255,100, 255)"); QWidget *rightWidget=new QWidget(); rightWidget->setStyleSheet("background-color: rgb(255,255, 100)"); QHBoxLayout *PHBoxLayout=new QHBoxLayout(this); PHBoxLayout->addWidget(leftWidget); PHBoxLayout->addWidget(rightWidget); QWidget *lefttopWidget=new QWidget(); lefttopWidget->setStyleSheet("background-color: rgb(100,255, 100)"); QWidget *leftdownWidget=new QWidget(); leftdownWidget->setStyleSheet("background-color: rgb(255,100, 100)"); QVBoxLayout *PHVBoxLayout=new QVBoxLayout(leftWidget); PHVBoxLayout->addWidget(lefttopWidget); PHVBoxLayout->addWidget(leftdownWidget); QWidget *rightleftWidget=new QWidget(); rightleftWidget->setStyleSheet("background-color: rgb(100,100, 100)"); QWidget *rightrightWidget=new QWidget(); rightrightWidget->setStyleSheet("background-color: rgb(155,100, 30)"); QHBoxLayout *PHHBoxLayout=new QHBoxLayout(rightWidget); PHHBoxLayout->addWidget(rightleftWidget); PHHBoxLayout->addWidget(rightrightWidget); }

最后代碼如下 就幾kb
鏈接:https://pan.baidu.com/s/1XenhRn2-qnuHzz_vo2BfHg
提取碼:88y3
復制這段內容后打開百度網盤手機App,操作更方便哦
