在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();
}