How to check the state of a checkbox when a button is clicked.
-
I am a newbie at QT. I have some experience with c++ for command line apps and python development. I want to grow my gui development skills. Now to the question. I have some basic code I am playing with to learn. On the ui I have a checkbox named ckbox. In the menu I have a menu item that I want to display two different messages depending on if the checkbox is clicked or not. Here is the code segment that I have right now for the menu item:
MenuItem { text: qsTr("&Message") onTriggered: if (ckbox.isChecked === True) { messageDialog.show(qsTr("If a witch floats,")) } else { messageDialog.show(qsTr("therefore she is made of wood.")) } }
The error I am getting is "ReferenceError: ckbox is not defined"
Thanks in advance for your help! Sorry if my code snippet didn't show up right. Still learning to use the editor tags.[edit: Fixed coding tags: thee back-ticks SGaist]
-
@alchemydragon Try
onTriggered: if (ckbox.checked == true) {messageDialog.show(qsTr("If ... floats,"))} else {messageDialog.show(qsTr("therefore ... wood."))}
or try
onTriggered: if (ckbox.checkedState == Qt.Checked) {messageDialog.show(qsTr("If ... floats,"))} else {messageDialog.show(qsTr("therefore ... wood."))}
and maybe you have to set
id: ckbox
in your CheckBox element
[EDIT] What do you mean "On the ui" -
I still get the error that ckbox is not defined. The ui is the user interface, the MainForum,ui,qml file. Thnaks for your suggestions.
-
Use
if (ui->ckbox->checked())
-
Sorry, typo. Should be:
if (ui->ckbox->isChecked())
-
@Brad-M i get an "unexpected token '>' with your suggestion. I tried changing the -> to a dot or just the dash and both times I got "ui is undefined" error.
-
@alchemydragon did you create the checkbox in the designer or in code?
-
@alchemydragon you need to check the name of your checkbox variable. If you created it with the designer it will be listed as the objectName in the property display panel. If you created it in code can you show me the code where it is declared? Re-reading your first post I see that ckbox is not defined so that is probably the wrong identifier.
-
@Brad-M I made it in Designer. I double checked the id box. It has ckbox. Sorry I am just now getting back to you. It has been busy at work this week.
4/9