我试图将一个简单的结构,从C ++推到QML,但是我似乎无法注册它:
messages.h
#pragma once
#include <QString>
#include <QMetaType>
struct Ticket {
Q_GADGET
Q_PROPERTY(QString name MEMBER name)
Q_PROPERTY(QString description MEMBER description)
public:
QString name;
QString description;
};
Q_DECLARE_METATYPE(Ticket);
我正在将其提供给QML:
main.cpp
#include <QtWidgets>
#include "MyWindow.h"
#include "messages.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<Ticket>("myself", 1, 0, "Ticket");
MyWindow the_window;
the_window.show();
return app.exec();
}
编辑:包括QML供参考
import QtQuick.Layouts 1.11
import QtQuick 2.11
RowLayout {
id: layout
property var tickets
onTicketsChanged: {
console.log("dum dum dum");
}
}
编译时,出现以下错误:
/Users/myself/lib/Qt/5.11.2/clang_64/lib/QtQml.framework/Headers/qqmlprivate.h:101:24: error: only virtual member
functions can be marked 'override'
~QQmlElement() override {
^
/Users/myself/lib/Qt/5.11.2/clang_64/lib/QtQml.framework/Headers/qqmlprivate.h:107:50: note: in instantiation of
template class 'QQmlPrivate::QQmlElement<Ticket>' requested here
void createInto(void *memory) { new (memory) QQmlElement<T>; }
^
/Users/myself/lib/Qt/5.11.2/clang_64/lib/QtQml.framework/Headers/qqml.h:292:33: note: in instantiation of function
template specialization 'QQmlPrivate::createInto<Ticket>' requested here
sizeof(T), QQmlPrivate::createInto<T>,
^
/Users/myself/dev/my_project/src/MyWindow.cpp:69:3: note: in instantiation of function template specialization
'qmlRegisterType<Ticket>' requested here
qmlRegisterType<Ticket>("myself", 1, 0, "Ticket");
^
1 error generated.
有没有一种方法可以在我的QML中提供Ticket结构,以便可以将值从C ++推送到QML?或者,有没有一种方法可以在qmlRegisterType的上下文中找出virtual member override
错误的含义?
答案 0 :(得分:2)
您不能使用Q_GADGETS
。您可以使它们众所周知(Q_DECLARE_METATYPE
,但是不能将它们注册为QML类型。一旦知道它们,您就可以使用它们,但是您不能在QML方面创建它们。
解决此问题的一种方法是,例如,使用一个带有(静态)成员函数的助手类(单例或上下文属性),返回您的小工具实例。
如果您还想创建它们,则必须使用Q_OBJECT
宏并从QObject
继承(注意Q_DECLARE_METATYPE
需要一个指针)。