将变量从C ++公开到QML [英] Expose variable from c++ to qml

查看:92
本文介绍了将变量从C ++公开到QML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
{
public:
    Program() = delete;
    Program(const QString &n, const QString &ip);
    Program(const Program &other) = delete;
    Program(Program &&other) = default;
    ~Program() = default;

    Program &operator=(const Program &other) = delete;
    Program &operator=(const Program &&other) = delete;

    constexpr static size_t maxProgram = 99;

private:
    QString name;
    QString imagePath;
};

您好,我想将此类中的变量 maxProgram 公开给QML,我认为在以下代码中它会起作用,但是我感谢其他干净的解决方案.

Hi, I want expose my variable maxProgram from this class to QML, I think thant in the following code its work but I appreciate other clean solution.

enum def {
    foo = maxProgram
};
Q_ENUM(def)

推荐答案

Qt有一个很好的文档,请首先搜索它们,而不是发布问题.

Qt have a good documentation search them first instead of posting a question.OverAll description Page and specific Answer.

C ++

class ApplicationData : public QObject
{
   Q_OBJECT
 public:
   Q_INVOKABLE QDateTime getCurrentDateTime() const {
    return QDateTime::currentDateTime();
   }
};

int main(int argc, char *argv[]) {
  QGuiApplication app(argc, argv);

  QQuickView view;

  ApplicationData data;
  view.rootContext()->setContextProperty("applicationData", &data);

  view.setSource(QUrl::fromLocalFile("MyItem.qml"));
  view.show();

  return app.exec();
}

QML

// MyItem.qml
import QtQuick 2.0

Text { text: applicationData.getCurrentDateTime() }

这篇关于将变量从C ++公开到QML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆