gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:04:59 26 4
gpt4 key购买 nike

我编写了一个简单的代码,以在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不是线程安全的,因此从辅助线程访问此信息很危险。在这种情况下,只需创建一个QObject即可映射CheckBox的更改:

    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
    }

    关于c++ - 在C++中的循环中读取QML对象(CheckBox)属性:始终相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60628889/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com