0
  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 文件中做同样的事情。

怎么做?

4

1 回答 1

0

在 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
}
于 2018-07-31T10:56:36.947 回答