PDA

View Full Version : Code improvement for yes/no popup message



nuliknol
23rd November 2016, 23:44
II have created my own yes-no popup dialog (because QtQuick2 doesn't have one) and I would like to ask if the code I made can be improved. I am asking because I am new in QML and I have the suspicion that I didn't engineer a good solution. So I would like your opinions.

This is the YesNoMsg.qml , that contains the popup:


import QtQuick 2.7
import QtQuick.Controls 2.0

Popup {
id: yesno_msg_popup
property string question
signal yesno_yes_pressed()
signal yesno_no_pressed()

Column {
Label {
id: yesno_msg_popup_title
text: question
}
Text {
id: yesno_msg_popup_text
}
Row {
Button {
id: yesno_msg_popup_yes_btn
text: "Yes"
onClicked: {
yesno_msg_popup.close()
yesno_msg_popup.yesno_yes_pressed()
}
}
Button {
id: yesno_msg_popup_no_btn
text: "No"
onClicked: {
yesno_msg_popup.close()
yesno_msg_popup.yesno_no_pressed()
}
}
}
}

}


And this is the code where I am using it:


Button {
text: "test dialog"
onClicked: {
yes_no_msg.question="yes or no?"
yes_no_msg.open()
yes_no_msg.yesno_yes_pressed.connect(yes)
yes_no_msg.yesno_no_pressed.connect(no)
}
function yes() {
console.log("yes")
yes_no_msg.yesno_yes_pressed.disconnect(yes)
yes_no_msg.yesno_no_pressed.disconnect(no)
}
function no() {
console.log("no");
yes_no_msg.yesno_yes_pressed.disconnect(yes)
yes_no_msg.yesno_no_pressed.disconnect(no)
}
}
YesNoMsg {
id: yes_no_msg
}

As you can see, I have to connect() and disconnect() everytime I use the yesno dialog and this is not very comfortable thing to do.

anda_skoa
24th November 2016, 10:28
You could just use the usual "on" syntax for signal handlers in the YesNoMsg element



YesNoMsg {
onYesNo_no_pressed:
}


Though I would recommend to also use more "normal" signal names, e.g. yesClicked() and noClicked()
The QtQuick.Controls 1.2 MessageDialog calls them yes() and no()

Maybe look at that for other inspiration as well http://doc.qt.io/qt-5/qml-qtquick-dialogs-messagedialog.html

Cheers,
_