问题
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