|
1Qter豆
工程目录结构:
pro 文件(在原代码的基础添加了):
QT += qml quick
main.cpp- #include <QCoreApplication>
- #include <QQmlEngine>
- #include <QQuickItem>
- #include <QDebug>
- class Message: public QObject
- {
- Q_OBJECT
- Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
- public:
- Message(){}
- ~Message(){}
- QString author() const { //读函数
- return m_author;
- }
- void setAuthor(const QString &a) { //写函数
- if(a != m_author) {
- m_author = a;
- emit authorChanged();
- }
- }
- signals:
- void authorChanged();
- private:
- QString m_author;
- };
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- QQmlEngine engine;
- Message msg;
- //实际运行时到此句编译出错,提示不完整的类 QQmlContext
- engine.rootContext()->setContextProperty("msg", &msg);
- QQmlComponent component(&engine, QUrl::fromLocalFile("myItem.qml"));
- component.create();
- return a.exec();
- }
复制代码
myItem.qml- import QtQuick 2.2
- Text {
- width: 100; height: 100
- text: msg.author //会调用 Message::author()
- Component.onCompleted: {
- msg.author = "John" //调用 Message::setAuthor()
- }
- }
复制代码 编译报错信息:
|
|