QT向界面中嵌套新的界面

简单说下 想要实现的内容

我们有一个主窗口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,操作更方便哦

 

转载于:https://www.cnblogs.com/bob-jianfeng/p/11609012.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值