我有一个小的 Qt/QML 项目,我尝试使用 C++ 枚举类。
主.cpp
int main(int argc, char *argv[])
{
qmlRegisterUncreatableType<shop::FruitShop>("FruitShop", 1, 0, "FruitShop", QStringLiteral("Sume shop"));
qRegisterMetaType<shop::FruitShop::Fruit>();
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
shop::FruitSetter setter;
engine.rootContext()->setContextProperty("_fruitSetter", &setter);
...
水果店.h
#include <QObject>
namespace shop {
class FruitShop : public QObject
{
Q_OBJECT
public:
enum class Fruit
{
Orange,
Apple,
Pear
};
Q_ENUM(Fruit)
explicit FruitShop(QObject *parent = nullptr);
};
} // namespace shop
水果设置者.h
#include <QObject>
#include "fruitshop.h"
namespace shop {
class FruitSetter : public QObject
{
Q_OBJECT
public:
explicit FruitSetter(QObject *parent = nullptr);
Q_INVOKABLE void setFruit(FruitShop::Fruit fruit);
};
} // namespace shop
main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
import FruitShop 1.0
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Button {
anchors.centerIn: parent
text: "Set Fruit"
onClicked: {_fruitSetter.setFruit(FruitShop.Apple)}
}
}
如果我在没有 namespace shop 的情况下使用,一切都可以。但如果我按照上面代码中的方式使用,则会出现错误
qrc:/main.qml:16:错误:未知的方法参数类型:FruitShop::Fruit
如何解决这个问题?
您还必须在 Q_INVOKABLE 的签名中包含命名空间:
Q_INVOKABLE void setFruit(shop::FruitShop::Fruit fruit)
这里也有解释:https://wiki.qt.io/How_to_use_a_C_class_declared_in_a_namespace_with_Q_PROPERTY_and_QML