SetProperty vs setContextProperty
-
I'm using qt quick controls 1.3. I have a working setup for communication between c++ and qml, but there are some things that I'd like to change which give me errors if I apply these changes. So I'd like to clear up a few things.
My test program does the following: When I press a button some text appears in the text area.
This is my class from myclass.h:
@
class menu_items : public QObject
{
Q_OBJECT
public:
QObject* text;
QObject* button;public slots:
void set_text ();
};
@In my main function I find pointers to QObject "text" and "button" and fill this class with them.
This is set_text function from myclass.cpp:
@
void menu_items::set_text()
{
text->setProperty("text", "This is text!");
}
@To change text I use setProperty. To assign function to button I use setContextProperty. This is code from main.cpp:
@
menu_items MENU;
QQmlContext* ctx = engine.rootContext();
ctx->setContextProperty("menu_items", &MENU);
@And this is qml code for my button:
@
Button
{
id: button1
objectName: "button1"
x: 550
y: 50
height: 25
text: qsTr("Press Me 1")
//onClicked: messageDialog.show(qsTr("You've pressed a button!"));
onClicked: menu_items.set_text();
}
@This works alright, but I'd like to know why some particular changes give me errors:
- When assigning a function to button I have to use setContextProperty. However, I want to use setProperty instead. But if I use something like
@button->setProperty("onClicked", &set_text());@
Compiler fails with error:
@c2102 & requires l-value@I want to use setProperty instead of setContextProperty because that way I don't have to edit qml file. In my current setup I had to specify onClicked event in qml. If it's possible, I'd like to be able fully control qml from c++ without having to edit qml.
- My class is in header file and class functions are in separate cpp file. I'd like to move everything to main cpp, but if I do that I get linker errors. Is header-cpp class structure mandatory for communication between qml adn c++?
Here are error codes:
@
LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall menu_items::metaObject(void)const " (?metaObject@menu_items@@UBEPBUQMetaObject@@XZ)LNK2001: unresolved external symbol "public: virtual void * __thiscall menu_items::qt_metacast(char const *)" (?qt_metacast@menu_items@@UAEPAXPBD@Z)
LNK2001: unresolved external symbol "public: virtual int __thiscall menu_items::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@menu_items@@UAEHW4Call@QMetaObject@@HPAPAX@Z)
@