在C ++中的循环中读取QML对象(CheckBox)属性:始终相同的值

问题描述 投票:0回答:1

我编写了一个简单的代码,以在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
c++ qt qml qtquick2
1个回答
0
投票

您有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
}
© www.soinside.com 2019 - 2024. All rights reserved.