2010-12-16 45 views
15

我想创建一个链中多个窗口:窗口1窗口2的父,窗口2窗口3等。当我关闭一个窗口,我想它的所有儿童,关闭以及母公司。目前,如果我关闭顶层窗口,所有其他人关闭,如希望的,但关闭,例如窗口2,只关闭窗口2,而不是窗口3等。我应该怎么做?谢谢你的帮助!Qt:父/子链中的多个窗口,父母不关闭孩子?

main_window.cpp

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) 
{ 
    QPushButton* button = new QPushButton("Open 1", this); 
    connect(button, SIGNAL(clicked()), this, SLOT(on_button_clicked())); 
} 

void MainWindow::on_button_clicked() { 
    window1 *w = new window1(this); 
    w->show(); 
} 

window1.cpp

window1::window1(QWidget *parent) : QWidget(parent) 
{ 
    this->setWindowFlags(Qt::Window); // in order to have a free-standing window 

    QPushButton* button = new QPushButton("Open 2", this); 
    connect(button, SIGNAL(clicked()), this, SLOT(on_button_clicked())); 
} 

void window1::on_button_clicked() { 
    window2 *w = new window2(this); 
    w->show(); 
} 

window2.cpp

window2::window2(QWidget *parent) : QWidget(parent) 
{ 
    this->setWindowFlags(Qt::Window); 

    QLabel* label = new QLabel("Window 2", this); 
} 

回答

16

默认的QApplication当最后一个主窗口(窗口没有父)被关闭(见QApplication::lastWindowClosed signal), ,之所以关闭是你的主窗口关闭一切退出。

关闭一个窗口小部件不会删除它,除非属性的Qt :: WA_DeleteOnClose设置(见QWidget::close())。如果你只是想让你的窗户关闭,我认为你必须重新实现closeEvent()来调用close()方法。

但是如果你想在关闭时删除它们,然后设置属性的Qt :: WA_DeleteOnClose。父母被删除时,孩子会自动删除。

+0

这样做伎俩!添加“w-> setAttribute(Qt :: WA_DeleteOnClose);”在上面的mainwindow.cpp中工作。很高兴我不必重新实施closeEvent。谢谢! – ishmael 2010-12-16 21:33:54

+0

我不知道这个小部件在默认情况下并没有关闭。这很有帮助。不知何故,为我的PySide窗口设置窗口属性为WA_DeleteOnClose解决了分段故障问题。现在我只需要弄清楚为什么... – lightalchemist 2012-04-26 06:22:46

3

您可以在每一个的应该有孩子部件超负荷closeEvent()。然后,要么让你的小工具的列表,以关闭closeEvent(),或只调用有deleteLater,这将有问题及其子删除这两个部件。

+0

我建议没有跟上孩子们的轨道,因为你可以简单地找到QMainWindow的孩子的closeEvent。 (当然,除非有孩子你不想关闭,否则这只是真的)为什么 – IceFire 2016-02-08 20:50:46

1

Leiaz已经指出了为什么儿童mainWindows'的closeEvent()没有被调用。 (。)如果你需要重载父主窗口中的closeEvent调用的closeEvent在每个孩子,因为你在那里做一些事情(如存储窗口设置),您可以将这个片段:

auto childList = findChildren<QMainWindow*>(); 
for (auto child : childList) 
{ 
    child->close(); 
} 

注意,儿童的QMainWindow孩子也会被调用,所以也不需要重载child-mainWindows的closeEvent。如果要只近QMainWindows是直接孩子,使用方法:

auto childList = findChildren<QMainWindow*>(QString(), Qt::FindDirectChildOnly); 
for (auto child : childList) 
{ 
    child->close(); 
}