03-07-2013 10:43 AM
Hi,
I want to implement simple toggle like functionality in QML.
For example, when user clicks once on the button, one action happens,
when user again clicks the button another action happens, when user again clicks
the button the action that happened initially will be performed.
How to keep state of such a variable in QML?
It should be smth like this, but don't know exactly how to do it:
onClicked: {
if (variable == true)
{
displayDialog();
variable = false;
}else
{
displayDialog2();
variable = true;
}
}
How to achieve it using correct syntax? Thank you.
Solved! Go to Solution.
03-07-2013 10:45 AM - edited 03-07-2013 10:57 AM
Hi,
Declare the variable as
property int someProperty: 0;
onClicked: {
if (variable == 0)
{
displayDialog()
variable = 1
}
else
{
displayDialog2()
variable = 0
}
}
You can also use enumerations, but they have to be exported from C++ code:
... in MyClass.h:
Q_ENUMS(MyEnum) enum MyEnum { EnumValue1 = 5, EnumValue2, EnumValue3 };
... in main.cpp: qmlRegisterType("MyLib", 1, 0, "MyClass");
... in qml: import MyLib 1.0 MyContainer { property int someProperty: MyClass.EnumValue1
Enums can also be faked in QML:
property int firstState: 0 property int secondState: 1 property int currentState: firstState
03-07-2013 10:47 AM - edited 03-07-2013 10:51 AM
Your syntax would work as long as you have set a boolean property variable somewhere that can be accessed within your file,
property bool variable
for the toggle you could just use,
variable = !variable
03-07-2013 11:07 AM
Hi,
it's not working
( :
Container {
...
property int toggleProperty: 0;
Button {
imageSource: "asset:///bkg.png"
onClicked: {
if (toggleProperty == 0)
{
doSmth() // this never gets called :((??
toggleProperty = 1
}
else
{
doSmthElse()
toggleProperty = 0
}
}
}
} // end of Container
03-07-2013 11:15 AM - edited 03-07-2013 11:23 AM
Reference the container by id, the following should work:
Container {
id: myContainer
...
property int toggleProperty: 0;
Button {
imageSource: "asset:///bkg.png"
onClicked: {
if (myContainer.toggleProperty == 0)
{
doSmth() // this never gets called :((??
myContainer.toggleProperty = 1
}
else
{
doSmthElse()
myContainer.toggleProperty = 0
}
}
}
} // end of Container
Another option is declaring property alias in top-level object:
Page {
property alias toggleProperty: myContainer.toggleProperty
...
This way even unqualified names will work:
if (toggleProperty == 0) ...
It's also possible to declare the int property itself at top level.