Search code examples
c++qtqdialogqmouseevent

Using QDialog inside MousePressEvent


I have a class, that subclasses QDialog without overriding exec(), accept() or reject() and another one, that calls the Dialog class inside its mousePaintEvent:

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

I have tried using the Dialog's existence for the check, but delete didn't really work(I put it after dialog.reject()), I even tried using a bool, which I, again, set to false after dialog.reject() in the last if, but I start to think, that nothing works after .reject(). How am I to proceed?


Solution

  • The problem with isVisible always returning false was due to it only returning true if all the ancestors are visible, as pointed here: http://doc.qt.io/qt-5/qwidget.html#visible-prop What I fail to grasp is why some of the ancestors (the class is child of a QWidget child of QTabWidget added from QDesigner) would not be marked as visible, as the are drawn on the screen. I did not get isVisible to show whether the widget is visible indeed(as it is) but I applied a workaround using a classical boolean approach:

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