访问除main.cpp之外的.cpp文件中的QMLEngine/rootObject属性


  1. 我在一个.qml文件中定义的一个面板中有两个单选按钮
  2. 无论是否在另一个QML文件或某个c++类的.cpp文件中检查,我都需要访问该属性
  3. 我可以在main.cpp中完成

使用下方的这些行

QQmlApplicationEngine engine;    
engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); 
if(engine.rootObjects().isEmpty())
return -1;
// Step 1: get access to the root object
QObject *rootObject = engine.rootObjects().first();
QObject *qmlObject_serial_radio = rootObject->findChild<QObject*>("serial_radio");
QObject *qmlObject_tcpip_radio = rootObject->findChild<QObject*>("tcpip_radio");    
// Step 2a: set or get the desired property value for the root object
qDebug() << qmlObject_serial_radio->property("checked");
qDebug() << qmlObject_tcpip_radio->property("checked");

但我想在其他.cpp文件中也这样做。

怎么做?

在C++中实例化QML对象可能是危险的,因为项目的生命周期不是在C++中直接处理的,所以QML可以在不通知它的情况下消除它们,例如创建和删除页面的StackView。

更好的方法是将C++对象导出到QML:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
class Helper: public QObject{
Q_OBJECT
Q_PROPERTY(bool isSerialEnabled READ isSerialEnabled WRITE setIsSerialEnabled NOTIFY isSerialEnabledChanged)
Q_PROPERTY(bool isTcpIpEnabled READ isTcpIpEnabled  WRITE setIsTcpIpEnabled  NOTIFY isTcpIpEnabledChanged)
public:
using QObject::QObject;
bool isSerialEnabled() const{
return mIsSerialEnabled;
}
void setIsSerialEnabled(bool isSerialEnabled){
if(mIsSerialEnabled == isSerialEnabled) return;
mIsSerialEnabled = isSerialEnabled;
emit isSerialEnabledChanged(mIsSerialEnabled);
}
bool isTcpIpEnabled () const{
return mIsTcpIpEnabled ;
}
void setIsTcpIpEnabled (bool isTcpIpEnabled ){
if(mIsTcpIpEnabled  == isTcpIpEnabled ) return;
mIsTcpIpEnabled = isTcpIpEnabled ;
emit isTcpIpEnabledChanged(mIsTcpIpEnabled );
}
signals:
void isSerialEnabledChanged(bool);
void isTcpIpEnabledChanged(bool);
private:
bool mIsSerialEnabled;
bool mIsTcpIpEnabled ;
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
Helper helper;
// check changes
QObject::connect(&helper, &Helper::isSerialEnabledChanged, [](bool isSerialEnabled){
qDebug()<<"isSerialEnabled"<<isSerialEnabled;
});
QObject::connect(&helper, &Helper::isTcpIpEnabledChanged, [](bool isSerialEnabled){
qDebug()<<"isTcpIpEnabledChanged"<<isSerialEnabled;
});
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("helper", &helper);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
#include "main.moc"

main.qml

RadioButton {
text: "Serial"
onCheckedChanged: helper.isSerialEnabled = checked
}
RadioButton {
text: "tcpip"
onCheckedChanged: helper.isTcpIpEnabled = checked
}

最新更新