Hi i am having difficulty in passing a struct from cpp to qml. Can someone give me some pointers. I am using qt 5.4/64 bit under debian lenny rc1. Here is what i have been working with which was just a new dialog project with the following added. Note the code seems to work if i pass it just a string but not with a simple struct.
my .h
namespace Ui {
class Dialog;
struct MyStruct {
int i;
};
}
Q_DECLARE_METATYPE(Ui::MyStruct)
#endif // DIALOG_H
namespace Ui {
class Dialog;
struct MyStruct {
int i;
QString name;
};
}
Q_DECLARE_METATYPE(Ui::MyStruct)
#endif // DIALOG_H
To copy to clipboard, switch view to plain text mode
.cpp file
ui(new Ui::Dialog)
{
ui->setupUi(this);
test();
}
void Dialog::test() {
using namespace Ui;
MyStruct test;
test.i=12;
test.name="Hello world";
QQmlEngine engine;
QQmlComponent component(&engine, "/home/user/projects-qt5/test_qml/MyItem.qml");
QObject *object
= component.
create();
qDebug() << "QML function returned:" << returnedValue.toString();
qDebug() << "comp error is " << component.errors();
delete object;
}
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
test();
}
void Dialog::test() {
using namespace Ui;
MyStruct test;
test.i=12;
test.name="Hello world";
QVariant v = QVariant::fromValue(test);
QQmlEngine engine;
QQmlComponent component(&engine, "/home/user/projects-qt5/test_qml/MyItem.qml");
QObject *object = component.create();
QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant,v));
qDebug() << "QML function returned:" << returnedValue.toString();
qDebug() << "comp error is " << component.errors();
delete object;
}
To copy to clipboard, switch view to plain text mode
.qml
import QtQuick 2.0
// MyItem.qml
Item {
function myQmlFunction(v) {
console.log("Got message:",v.name)
return "some return value"
}
}
import QtQuick 2.0
// MyItem.qml
Item {
function myQmlFunction(v) {
console.log("Got message:",v.name)
return "some return value"
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks