在 MousePressEvent 中使用 QDialog

Using QDialog inside MousePressEvent

我有一个 class,subclasses QDialog 没有覆盖 exec()accept()reject() 和另一个,在其 mousePaintEvent:

中调用 Dialog class
void Canvas::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton){
        if (dialog->isVisible()){
            dialog->setModal(true);
            dialog->move(QWidget::mapToGlobal(event->pos()));
             //I connect the dialog's accepted signal to the CallingClass's slot, that uses the information taken from the dialog
            connect(dialog, &Dialog::accepted, this, &CallingClass::slot);
            dialog->exec();
        }
    }
    if (dialog->isVisible()){
        if (dialog->rect().contains(event->pos())){
            dialog->reject();
        }
    }
}

我试过使用对话框的存在性来检查,但是 delete 并没有真正起作用(我把它放在 dialog.reject() 之后),我什至尝试使用 bool,我,再次,在最后一个 if 中的 dialog.reject() 之后设置为 false,但我开始认为,在 .reject() 之后没有任何效果。我该如何进行?

我的理解是 dialog->rect() 不会给你你想要的(见 this). Unfortunately I can not test it right now, but I think you should try to use it in combination with pos or try directly to use frameGeometry)。有了这个你将有你的 window 相对于它的真实位置和大小parent。尝试查看您从点击事件中获取的坐标值以及从这些方法中获取的值,以便弄清楚如何使用它们...基本上您需要决定是否使用全局坐标相对于你的桌面 parent window.

isVisible 始终返回 false 的问题是因为它仅在所有祖先可见时才返回 true,如此处指出: http://doc.qt.io/qt-5/qwidget.html#visible-prop 我无法理解的是为什么某些祖先(class 是从 QDesigner 添加的 QTabWidget 的 QWidget 子级的子级)不会被标记为可见,因为它们是在屏幕上绘制的。我没有得到 isVisible 来显示小部件是否确实可见(因为它是)但我使用 classical 布尔方法应用了一个解决方法:

void Class::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton){
        if (!dialogOpened){
            dialog->show();
            dialogOpened = true;
        } else {
            dialog->hide();
            dialogOpened = false;
        }
    }
}