将变量从C ++公开到QML

时间:2018-07-11 13:28:17

标签: c++ qt qml c++17

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,我认为在下面的代码中它会起作用,但是我感谢其他干净的解决方案。

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

2 个答案:

答案 0 :(得分:1)

使用带有CONSTANT属性的Q_PROPERTY:

Q_PROPERTY(int maxProgram READ getMaxProgram CONSTANT)

...

private:
    int getMaxProgram() const {
        return maxProgram;
    }

size_t不起作用,但是从5.10开始,您可以使用qsizetype

答案 1 :(得分:1)

Qt有一个很好的文档,请先搜索它们,而不是发布问题。OverAll description Page和特定的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() }