Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QtQuickControls2 Dialog vanishing on click outside

I am trying to use a QtQuickControls2 Dialog:

    Dialog {
        id: dialog
        x: parent.width/2-width/2
        y: parent.height/2-height/2
        width:300
        height:200
        title: "Warning"
        modal: true
        standardButtons: Dialog.Ok
        visible: false
        onAccepted: console.log("Ok clicked")
    }


    Button {
        id: button
        objectName: "doSomethingButton"
        onClicked: {
            if(problemFlag==true)
                dialog.visible=true
        }
    }

It should be triggered if the button is clicked and problemFlag is true. I read that if modal is set to true the user cannot interact with the rest of the program. However, if I click somewhere outside the Dialog, it vanishes (without the need of clicking OK).

like image 612
numberCruncher Avatar asked Apr 12 '18 16:04

numberCruncher


1 Answers

I ran into this too. You need to set the closePolicy so that it only closes when the escape key is pressed:

closePolicy: Popup.CloseOnEscape

The docs mention this:

This property holds whether the popup is modal.

Modal popups often have a distinctive background dimming effect defined in overlay.modal, and do not allow press or release events through to items beneath them.

On desktop platforms, it is common for modal popups to be closed only when the escape key is pressed. To achieve this behavior, set closePolicy to Popup.CloseOnEscape.

The default value is false.

The distinction is hard to see, but it's there: modal popups don't allow press or release events through to items beneath them, but it doesn't mean that they won't close.

I can't remember the reasoning behind this, but if I had to guess, I'd say it's to do with the fact that Qt Quick Controls 2 were built for mobile first. On mobile, you typically:

  1. Want dimming effects for a popup.
  2. Don't want touch events that occur outside of it to go through to items below it.
  3. Want the popup to close when the user taps outside of it.

If you take a look at widgets, the docs for QDialog::modal say:

Setting this property to true is equivalent to setting QWidget::windowModality to Qt::ApplicationModal.

If you then look at Qt::WindowModality:

This enum specifies the behavior of a modal window. A modal window is one that blocks input to other windows. [...]

and:

The window is modal to the application and blocks input to all windows.

So although modal QDialogs don't close when clicks occur outside of them, the distinction between not letting events through and not closing is not a new one.

like image 145
Mitch Avatar answered Oct 19 '22 02:10

Mitch