关于qt窗体之间相互覆盖的问题

本文分析了Qt中由于子类初始化时父对象设置错误导致控件失效的情况,提供两种解决策略:调整UI的父对象或隐藏子窗体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在qt界面的开发中,可能会遇到如下问题:新建的一个窗体会导致之前创建窗体的控件无法正常交互。

先看代码,定义了两个类AppDownloadWidget与Widget。

//Widget类
QWidget *w_Main;
AppDownloadWidget *w_AppDownload;
void Widget::Init()
{
    w_Main=new QWidget(this);
    w_AppDownload = new AppDownloadWidget(this);
    w_AppDownload->Init(this);
}


//AppDownloadWidget类
Widget *ptr_main;
QWidget *w_Application;
AppDownloadWidget::AppDownloadWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AppDownloadWidget)
{
    ui->setupUi(this);
    ptr_main = (Widget *)parentWidget();
}

void AppDownloadWidget::Init(QWidget *parent)
{
     w_Application = new QWidget(parent);
}

此时会导致虽然Widget类的控件可以正常显示,但控件却无法正常交互,如Widget类的按钮控件无法点击等。

这个现象是由于ui没有指定好父对象导致的。在Widget::Init()中,首先创建了一个w_Main窗体,父对象为this,即当前类本身。其次实例化了类对象w_AppDownload,父对象也为当前类本身,然后调用了w_AppDownload类的成员函数init进行初始化。

在AppDownloadWidget::Init(QWidget *parent)中,创建了一个w_Application 窗体,父对象为形参parent,由于调用AppDownloadWidget::Init时实参为this,即Widget类,所以w_Application窗体指针的父类为Widget类。

此时就会产生一个问题,在Widget类中new出来的w_AppDownload,会使AppDownloadWidget类的构造函数的parent指针指向Widget类,并且AppDownloadWidget::init中new出来的对象父类也是Widget类,而AppDownloadWidget类的构造函数中的函数setupUi(this)会把ui界面的父对象设置为this,即当前类AppDownloadWidget。这就导致了实际的AppDownloadWidget的ui界面覆盖了Widget的界面,虽然Widget的控件能看见,但无法交互,因为有一个隐形的窗体阻挡了控件的交互。

此时有两种解决方法:

1.在ui里找到AppDownloadWidget的ui,把窗体大小设置为0,0。

2.修改AppDownloadWidget的构造函数,调整ui的父对象。

AppDownloadWidget::AppDownloadWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AppDownloadWidget)
{
    ui->setupUi(this);
    ptr_main = (Widget *)parentWidget();
}

//修改为
AppDownloadWidget::AppDownloadWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AppDownloadWidget)
{
    ui->setupUi(parent);
    ptr_main = (Widget *)parentWidget();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值