Qt 4.8.5 QML 与 QT C++ 嵌套
目前在 Qt4.8.5 中测试成功
Defining New QML Elements
While new QML elements can be defined in QML, they can also be defined by C++ classes; in fact, many of the core QML Elements are implemented through C++ classes. When you create a QML object using one of these elements, you are simply creating an instance of a QObject-based C++ class and setting its properties.
To create a visual item that fits in with the Qt Quick elements, base your class off QDeclarativeItem instead of QObject directly. You can then implement your own painting and functionality like any other QGraphicsObject. Note that QGraphicsItem::ItemHasNoContents is set by default on QDeclarativeItem because it does not paint anything; you will need to clear this if your item is supposed to paint anything (as opposed to being solely for input handling or logical grouping).
For example, here is an ImageViewer class with an image URL property:
#include <QtCore>
#include <QtDeclarative>
class ImageViewer : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY(QUrl image READ image WRITE setImage NOTIFY imageChanged)
public:
void setImage(const QUrl &url);
QUrl image() const;
signals:
void imageChanged();
};
Aside from the fact that it inherits QDeclarativeItem, this is an ordinary class that could exist outside of QML. However, once it is registered with the QML engine using qmlRegisterType():
qmlRegisterType<ImageViewer>("MyLibrary", 1, 0, "ImageViewer");
Then, any QML code loaded by your C++ application or plugin can create and manipulate ImageViewer objects:
import MyLibrary 1.0
ImageViewer { image: "smile.png" }
It is advised that you avoid using QGraphicsItem functionality beyond the properties documented in QDeclarativeItem. This is because the GraphicsView backend is intended to be an implementation detail for QML, so the QtQuick items can be moved to faster backends as they become available with no change from a QML perspective. To minimize any porting requirements for custom visual items, try to stick to the documented properties in QDeclarativeItem where possible. Properties QDeclarativeItem inherits but doesn't document are classed as implementation details; they are not officially supported and may disappear between releases.
Note that custom C++ types do not have to inherit from QDeclarativeItem; this is only necessary if it is a displayable item. If the item is not displayable, it can simply inherit from QObject.
For more information on defining new QML elements, see the Writing QML extensions with C++ tutorial and the Extending QML Functionalities using C++ reference documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
上一篇: Qt 5.4 moc 元对象编译器
下一篇: Covenant 利用分析
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论