问题描述:在一个QWidget窗口类中设置其为工具窗口(Qt::Tool)。在它之中显示其他窗口,当关闭这些窗口的最后一个时,会自动析构此窗口。
#include "test.h"
test::test(QWidget *parent) : QWidget(parent)
{
setWindowFlags(Qt::Tool);
QPixmap image(":/headportrait/head.jpg");
ChatFriend *chat = new ChatFriend(123456,image,"nnn");
chat->show();
}
ChatFriend 是我写的一个继承QWidget的类。在关闭ChatFriend时是调用close()。上面代码执行后,关闭chat窗口,test窗口直接析构了。这个问题出现好久了,当时没定位到这,还以为是多线程引起的访问野指针导致程序崩了,仔细看了n多遍代码未果。终于在今天夜里定位到此问题,也终于得到解决。
解决方法:将ChatFriend类设置窗口类型加一个Qt::CoverWindow。
#include "test.h"
test::test(QWidget *parent) : QWidget(parent)
{
setWindowFlags(Qt::Tool);
QPixmap image(":/headportrait/head.jpg");
ChatFriend *chat = new ChatFriend(123456,image,"nnn");
chat->setWindowFlag(Qt::CoverWindow);
chat->show();
}
Qt::CoverWindow文档描述:Indicates that the window represents a cover window, which is shown when the application is minimized on some platforms.
可能是将chat认为是最后一个主窗口了,所以close后直接析构了test。封面窗口可能不算是一个主窗口了。有大佬知晓其缘由赐教一下。