我编写了一个简单的代码,以在C ++循环中从我的QML读取复选框的值。但是,即使使用鼠标切换复选框,我也始终会得到“未经检查”的值。
QML:
CheckBox {
objectName: "simulatorCheckbox"
text: "text"
}
C ++:
QObject *rootObject = engine.rootObjects().first();
QObject *simulatorCheckboxQ = rootObject->findChild<QObject*>("simulatorCheckbox");
if (!simulatorCheckboxQ) {
std::cout << "simulatorCheckboxQ not found" << std::endl;
std::exit(1);
}
auto consume = [&simulatorCheckboxQ]() {
while(true) {
QVariant simulatorCheckboxState = simulatorCheckboxQ->property("checkedState");
int simulatorCheckboxStateInt = simulatorCheckboxState.toInt();
if (simulatorCheckboxStateInt==Qt::Unchecked) {
std::cout << "UNchecked!" << std::endl;
} else if (simulatorCheckboxStateInt==Qt::Checked) {
std::cout << "checked!" << std::endl;
} else if (simulatorCheckboxStateInt==Qt::PartiallyChecked) {
std::cout << "PARTIALLY checked!" << std::endl;
}
//delay...
}
};
//run consume as thread
您有2种不良做法:
请勿从C ++访问QML元素,因为这可能很危险。
您不应该使用while循环,也请考虑最后一个选项线程。
在这种情况下,GUI不是线程安全的,因此从辅助线程访问此信息很危险。在这种情况下,只需创建一个映射CheckBox更改的QObject:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
class CheckBoxMapper: public QObject{
Q_OBJECT
Q_PROPERTY(Qt::CheckState state READ state WRITE setState NOTIFY stateChanged)
public:
using QObject::QObject;
Qt::CheckState state() const{
return m_state;
}
public slots:
void setState(Qt::CheckState state){
if (m_state == state)
return;
m_state = state;
emit stateChanged(m_state);
}
signals:
void stateChanged(Qt::CheckState state);
private:
Qt::CheckState m_state;
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
CheckBoxMapper checkboxMapper;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("checkboxMapper", &checkboxMapper);
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);
QObject::connect(&checkboxMapper, &CheckBoxMapper::stateChanged, [](Qt::CheckState state){
qDebug() << state;
});
return app.exec();
}
#include "main.moc"
main.qml
CheckBox {
text: "text"
onCheckStateChanged: checkboxMapper.state = checkState
Component.onCompleted: checkboxMapper.state = checkState
}