【问题标题】:How to add C++ QQuickPaintedItem in QML如何在 QML 中添加 C++ QQuickPaintedItem
【发布时间】:2022-11-02 21:16:09
【问题描述】:

我想像这样添加 C++ 类缺口矩形.hpp到 QML:

#ifndef NOTCHEDRECTANGLE_HPP
#define NOTCHEDRECTANGLE_HPP

#include <QtQml/qqmlregistration.h>
#include <QQuickPaintedItem>

class NotchedRectangle : public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
    QML_ELEMENT
public:
    NotchedRectangle();

    void paint(QPainter* painter) override;

    QColor color() const;
    void setColor(QColor color);

signals:
    void colorChanged();

private:
    QColor m_color;
};

#endif // NOTCHEDRECTANGLE_HPP

我有 qmake 构建系统,但不知道 - 我应该在 qmake 文件中添加什么。

我的文件系统如下所示:

我试图将这个字符串添加到 qmake 文件中:

CONFIG += qmltypes
QML_IMPORT_NAME = UI.NR
QML_IMPORT_MAJOR_VERSION = 1
INCLUDEPATH += UI/NotchedRectangle

但它们会导致错误:

[Makefile.Debug:1175: qlauncher_metatypes.json] 错误 1

你能帮我吗?

【问题讨论】:

  • 请创建一个minimal reproducible example
  • 你应该使用qmlRegisterType
  • @m7913d 我使用了 qmlRegisterType - 它工作正常。但这是旧技术,Qt Designer 不支持
  • @m7913d 在Qt5.15 之后它实际上是旧的。 (reference)
  • @SMR 谢谢,但是有很多自定义 C++ 对象。 NotchedRectangle 是最简单和最好的例子。我在没有 Qt Designer 的情况下使用了 qmlRegisterType。但现在我想添加对 Qt Designer 的支持并使用现代功能 :)

标签: c++ qt qml qmake qt6


【解决方案1】:

你应该在暴露类后导入 qml 文件:

import UI.NR 1.0

我建议您将 UI.NR 更改为其中没有点的其他内容。

然后举个例子:

随便你叫什么{

}

【讨论】:

  • 如果未指定名称,将使用类名 (NotchedRectangle)。虚线名称也不是问题。
  • 如果我不编辑 qmake 文件 - 我在 QML 中有错误“未知模块”。否则 - 我有错误:[Makefile.Debug:1175: qlauncher_metatypes.json] 错误 1
  • 是的,您总是可以忽略 qml 代码约定,因为这不是问题。无论如何,这使您成为特殊的程序员。至于你的问题@SlimRG,为什么你坚持使用 QML_ELEMENT 将 c++ 类暴露给 qml?你不能在 main.cpp 中使用 qmlRegisterType 吗?然后你可以做我上面写的。
【解决方案2】:

QML_IMPORT_NAME 不是类名!

它是包的名称,必须不同。

我使用“自定义”。

接下来你必须在 main.cpp 中包含类

最后 - 你应该做回覆编译

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多