要将QML与C++连接起来,而不使用单例模式,可以使用以下方法:
C++代码示例:
#include
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject(QObject *parent = nullptr) : QObject(parent) {}
public slots:
void mySlot() {
// 处理QML调用的逻辑
}
};
在main.cpp中将MyObject设置为QML的上下文对象:
#include
#include
#include "myobject.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MyObject myObject;
engine.rootContext()->setContextProperty("myObject", &myObject);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
在QML中,可以通过调用myObject对象的方法来触发C++中的槽函数:
Button {
text: "Click"
onClicked: myObject.mySlot()
}
C++代码示例:
#include
class MyGlobals : public QObject
{
Q_OBJECT
Q_PROPERTY(QString myProperty READ myProperty WRITE setMyProperty NOTIFY myPropertyChanged)
public:
static MyGlobals& instance() {
static MyGlobals instance;
return instance;
}
QString myProperty() const {
return m_myProperty;
}
void setMyProperty(const QString& value) {
if (value != m_myProperty) {
m_myProperty = value;
emit myPropertyChanged();
}
}
signals:
void myPropertyChanged();
private:
MyGlobals(QObject *parent = nullptr) : QObject(parent) {}
QString m_myProperty;
};
在main.cpp中将MyGlobals设置为QML的上下文属性:
#include
#include
#include "myglobals.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("myGlobals", &MyGlobals::instance());
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
在QML中,可以直接访问myGlobals对象的属性来与C++通信:
Text {
text: myGlobals.myProperty
Component.onCompleted: {
myGlobals.myProperty = "Hello World"
}
}
这些方法可以让你在不使用单例模式的情况下将QML与C++连接起来。请根据你的需求选择适合的方法。
上一篇:不使用单个大括号进行字符串匹配。
下一篇:不使用单选按钮的多选提交按钮