在 C++ 中实例化 QML 对象可能很危险,因为项目的生命周期不是直接在 C++ 中处理的,因此 QML 可以在不通知它的情况下消除它们,例如创建和删除页面的 StackView。
更好的方法是将 C++ 对象导出到 QML:
主文件
#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
}