QWidget 未关闭 - 留空 window

QWidget not closing - leaving empty window

我对 QWidget 派生 (NewPayment) 有疑问。这是一个简单的 window,带有一些控件和一个 QDialogButtonBox。它有 2 个插槽:

void NewPayment::on_buttonBox_accepted() {
    //(some action going in here)
    this->close();
} 

void NewPayment::on_buttonBox_rejected() {
    this->close();
}

当我单击“确定”或“取消”时 - 插槽按预期触发。问题是 window 没有关闭 。所有内容都消失了,只剩下一个空的 window(剩下 window 标题)。

小部件作为 MDISubwindow 存在,创建方式如下:

void HurBudClientGUI::addNewPayment(int direction, int contractorid) {
    foreach(QMdiSubWindow* it, this->ui.mainArea->subWindowList()) {
        if ( NewPayment* np = qobject_cast<NewPayment*>( it->widget() )  ) {
            if (np->getContractorID() == contractorid) {
                this->ui.mainArea->setActiveSubWindow(it);
                return;
            }
        }
    }
    NewPayment* np = new NewPayment(direction, contractorid, this);
    np->setAttribute(Qt::WA_DeleteOnClose);
    this->ui.mainArea->addSubWindow(np);
    np->show();
}

有趣的是,当我:

window 已正确关闭。我已经为我的 class:

覆盖了一个 QWidget::closeEvent(QCloseEvent * event)
void NewPayment::closeEvent(QCloseEvent * event) {
    qDebug() << "[" << __FUNCTION__ << "]:" << "event: " << event  << "; sender:" << sender();
}

它每次都显示几乎相同的事件 - 无论我如何尝试关闭它:

[ NewPayment::closeEvent ]: event:  QCloseEvent(Close, 0x40bd64, type = 19) ; sender: QDialogButtonBox(0x4dfa7a8, name = "buttonBox") // I hit cancel
[ NewPayment::closeEvent ]: event:  QCloseEvent(Close, 0x40b634, type = 19) ; sender: QObject(0x0) // I hit the 'X' in the window corner
[ NewPayment::closeEvent ]: event:  QCloseEvent(Close, 0x40b468, type = 19) ; sender: QObject(0x0) // I hit "close active sub window" from parent window
[ NewPayment::closeEvent ]: event:  QCloseEvent(Close, 0x40b454, type = 19) ; sender: QObject(0x0)  // I hit "close all sub windows" from parent window

最好的部分是,当我点击 "cancel"(windows 被清除,但保持打开状态),然后点击 "X" 或其他任何东西 - window 已关闭,但控制不会通过我的 NewPayment::closeEvent(我在那里有一个刹车点 - 它不会触发)。

它在其他 windows 中的工作原理非常相似。奇怪的是,我很确定它之前(+- 一周前)对其他 windows 有效(它们在单击 OK ant 执行所有必要操作后关闭)。我想我最终会从 SVN 分析差异,但也许有人有类似的问题?我最近睡眠很少,所以也许我错过了一些微不足道的事情?

如有任何帮助,我将不胜感激。

您指望什么,小部件不是 window。您可以通过关闭小部件获得输出,但这与关闭 window 不同。

如果要关闭它,您需要有 window 的句柄。你可以:

  • 保留从 addSubWindow()
  • 返回的指针
  • 提前创建window,创建父级为window的widget,将window的widget设置为widget,然后使用widget的parent() 访问 window.

我听从了@ddriver 的建议,最后得到了

void NewPayment::on_buttonBox_rejected() {
    if (QMdiSubWindow* psw = qobject_cast<QMdiSubWindow*>(this->parent()) ) {
        psw->close();
    } else {
        this->close();
    }
}

现在它可以正常工作了。