Доступ к свойствам QMLEngine / rootObject в файлах .cpp, кроме main.cpp

  1. У меня есть две радио кнопки на одной панели, определенные в одном файле .qml.
  2. Мне нужно получить доступ к свойству, независимо от того, установлено оно или нет в другом файле QML или в файле .cpp некоторого класса C ++.
  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.

как это сделать?

0

Решение

Создание экземпляров объектов QML в C ++ может быть опасным, поскольку жизненный цикл элементов не обрабатывается непосредственно в 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
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]