Expose variable from c++ to qml

£可爱£侵袭症+ 提交于 2021-01-28 14:00:37

问题


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;
};

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)

回答1:


Use Q_PROPERTY with the CONSTANT attribute:

Q_PROPERTY(int maxProgram READ getMaxProgram CONSTANT)

...

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

size_t won't work, but since 5.10 you can use qsizetype




回答2:


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() }


来源:https://stackoverflow.com/questions/51286723/expose-variable-from-c-to-qml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!