3

I'm trying to show an QML MessageDialog with Qt 6.4.3. This dialog should be closed with the provided button.

import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs

ApplicationWindow  {
    id: window

    width: 800
    height: 600

    visible: true

    title: qsTr("Hello World")

    Component.onCompleted: dialog.open()

    MessageDialog{
        id: dialog

        modality: Qt.ApplicationModal

        title: "Test Dialog"
        text: "My Text"

        buttons: MessageDialog.Ok
    }
}

PROBLEM: The dialog is dismissed, if the user clickes outside the dialog. I would expect the dialog to stay visible until the user pressed the OK button.

What is my mistake in the following example? How can I achieve, that the dialog stays visible until the user pressed the button?

Jürgen Lutz
  • 329
  • 1
  • 1
  • 10

1 Answers1

2

If you're interested in a workaround, you can force the dialog to stay up until the user accepts by catching the reject and forcing the dialog to open again:

import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs
Page {
    MessageDialog{
        id: dialog
        modality: Qt.ApplicationModal
        title: "Test Dialog"
        text: "My Text"
        buttons: MessageDialog.Ok
        onRejected: Qt.callLater(dialog.open)
    }
    Button {
        text: qsTr("Open")
        anchors.horizontalCenter: parent.horizontalCenter
        y: parent.height * 2 / 10
        onClicked: dialog.open()
    }
}

You can Try it Online!

Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
  • Thanks for this workaround. This is working for a dialog with just having a OK-Button. If you have a CANCEL-Button as well, this is not working, because you can't dismiss the dialog in this case. – Jürgen Lutz Mar 27 '23 at 05:46
  • @JürgenLutz for the OK-CANCEL scenario, you have several additional workarounds. Either transition to a YES-NO question. Or, you can consider implementing you can consider replacing the standard buttons with your own by writing `footer: RowLayout { Button ... }`. That way you can differentiate a cancel-button-click versus onRejected and handle each case appropriately. – Stephen Quan Mar 27 '23 at 07:35
  • 1
    Sure. But I will leave it like it is for now. Hopefully they will fix the bug I have reported (https://bugreports.qt.io/browse/QTBUG-112328) – Jürgen Lutz Mar 27 '23 at 14:14