Usage of QString in QML
-
i have a class ABC.cpp which has function called Test(QString index) looks like
void ABC :: Test(QString index).In XYZ.qml i am trying to access above in qml like
ABC.Test("Hello"); -> works fine but
when i declare that in constants.qml like
readonly property string TXT_HELLO: "Hello"
and use as below
ABC.Test("Constants.TXT_HELLO");
it doesnot work where i am wrong. -
You already have the
property
so you can use it directly in your function without" "
ABC.Test(TXT_HELLO);
can you please tell us what is
Constants
you are referring to ?Below is some sample code...
TestString.h :
public slots: void printQmlString(const QString &str);
TestString.cpp:
void TestString::printQmlString(const QString &str) { qDebug() << Q_FUNC_INFO << str << endl; }
main.cpp:
TestString ts; engine.rootContext()->setContextProperty("TS", &ts);
QML:
import QtQuick 2.6 import QtQuick.Window 2.2 Window { id: root visible: true width: 640 height: 480 title: qsTr("Hello World") readonly property string myString: 'Hallo Qt, :)' /* ...*/ Component.onCompleted: TS.printQmlString(root.myString) }
Output:
All the best.
-
i am sorry i will be more clear now :
ABC class has a function called toolbarButtonClick:
void ABC::toolbarButtonClick(QString index)
{}
Constants.qml is a file where i am thinking to keep all the strings at one place
looks like :import QtQuick 2.0
pragma SingletonQtObject {
readonly property string TXT_HELLO: "Hello"
readonly property string TXT_WORLD: "World"
}For ToolbarButton i need to have Buttonclick
ToolbarButton {
label: qsTr("toolbutton")onButtonClick: {
ABC.toolbarButtonClick(Constants.TXT_HELLO)
}
onButtonLongPress: {
ABC.toolbarLongPress(Constants.TXT_HELLO)
}
}When i use like above i dont get click event
if i use directly strings like below it will take click event
onButtonClick: {
ABC.toolbarButtonClick("Hello")
}
onButtonLongPress: {
ABC.toolbarLongPress("Hello")
} -
@sush123 said in Usage of QString in QML:
Constants
Please tell me do you have any error on
buttonClick()
&buttonLongPress()
?something like below :
ReferenceError: Constants is not defined
-
Please register your Constants.qml singleton before you use it.
refer
qmlRegisterSingletonType
- QQmlEngine Class.below is sample code for the solution:
main.cpp
qmlRegisterSingletonType(QUrl("qrc:/Constants.qml"), "singleton", 1, 0, "Consts");
Constants.qml is same as you used
pragma Singleton import QtQuick 2.0 QtObject { readonly property string click: 'Mouse Click' readonly property string pressHold: 'Mouse PressHold' }
and then as below example
MouseArea { anchors.fill: parent onClicked: { console.log("Inside QML Mouse Click") TS.printQmlString(Consts.click) } onPressAndHold: { console.log("Inside QML Mouse Press&Hold") TS.printQmlString(Consts.pressHold) } }
Output :
Hope this helps :)
All the best. -
Thanks alot i registered using wrong type,
qmlRegisterSingletonType(QUrl("qrc:/Constants.qml"), "singleton", 1, 0, "Consts"); helped me