找回密码
 立即注册
收起左侧

QML使用C++类提示不完整的QQmlcontext

2
回复
7257
查看
[复制链接]
累计签到:22 天
连续签到:1 天
来源: 2017-7-13 12:08:02 显示全部楼层 |阅读模式
1Qter豆
工程目录结构:

pro 文件(在原代码的基础添加了):
QT += qml quick
main.cpp
  1. #include <QCoreApplication>
  2. #include <QQmlEngine>
  3. #include <QQuickItem>
  4. #include <QDebug>

  5. class Message: public QObject
  6. {
  7.     Q_OBJECT
  8.     Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)

  9. public:
  10.     Message(){}
  11.     ~Message(){}
  12.     QString author() const { //读函数
  13.         return m_author;
  14.     }

  15.     void setAuthor(const QString &a) { //写函数
  16.         if(a != m_author) {
  17.             m_author = a;
  18.             emit authorChanged();
  19.         }
  20.     }

  21. signals:
  22.     void authorChanged();

  23. private:
  24.     QString m_author;
  25. };


  26. int main(int argc, char *argv[])
  27. {
  28.     QCoreApplication a(argc, argv);

  29.     QQmlEngine engine;
  30.     Message msg;
  31.     //实际运行时到此句编译出错,提示不完整的类 QQmlContext
  32.     engine.rootContext()->setContextProperty("msg", &msg);
  33.     QQmlComponent component(&engine, QUrl::fromLocalFile("myItem.qml"));
  34.     component.create();

  35.     return a.exec();
  36. }
复制代码

myItem.qml
  1. import QtQuick 2.2

  2. Text {
  3.     width: 100; height: 100
  4.     text: msg.author //会调用 Message::author()
  5.     Component.onCompleted: {
  6.         msg.author = "John" //调用 Message::setAuthor()
  7.     }
  8. }
复制代码
编译报错信息:

附件: 您需要 登录 才可以下载或查看,没有帐号?立即注册
回复

使用道具 举报

尚未签到

2017-7-15 10:22:51 显示全部楼层
开始那个不能用qcoreapplication吧,起码要qguiapplication或直接qapplication(这个需要widgets支持)

点评

谢谢了,我试试。  发表于 2017-9-14 15:38
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

公告
可以关注我们的微信公众号yafeilinux_friends获取最新动态,或者加入QQ会员群进行交流:190741849、186601429(已满) 我知道了