Conditionally closing a dialog
Unsolved
QML and Qt Quick
-
I'm writing a program that includes a dialog that requires some user input, like so:
import QtQuick 2.12 import QtQuick.Controls 2.12 import QtQuick.Layouts 1.12 Dialog { id: foobar function show() { input.text = "" input.forceActiveFocus(Qt.PopupFocusReason) open() } title: "Foobar" modal: true width: 350 standardButtons: Dialog.Ok | Dialog.Cancel onAccepted: console.log("foobar: ", input.text) contentItem: RowLayout { spacing: 10 Label { text: "Number of pages:" } TextField { id: input validator: IntValidator {} placeholderText: "1234" Layout.fillWidth: true } } }
Without having to implement a custom footer such as a
DialogButtonBox
, I'd like to override theaccepted()
signal to only continue being accepted if the user has put something ininput.text
. Ifinput.text
is null, I want to stop the dialog from closing.Apologies if I'm not making myself clear; I will be happy to provide any details necessary. I'm using Qt 5.15.2 on Linux.
-
I also needed this but there was no answer for it anywhere.
Here is my solution:Dialog { id: loginDialog title: "Login" modal: true LoginDialog { id: loginPage anchors.fill: parent } footer: DialogButtonBox { id: buttons Button { id: okButton text: qsTr("Ok") DialogButtonBox.buttonRole: DialogButtonBox.InvalidRole Connections { target: okButton function onClicked() { if (CONDITION){ loginDialog.accept() } else { } } } } Button { id: cancelButton text: qsTr("Cancel") DialogButtonBox.buttonRole: DialogButtonBox.RejectRole } } }
So my answer is replace standard buttons and handle button clicks yourself.