[英]Routinely change QML property value from within a threaded c++ loop
I'm brand new to c++ and QML, and am struggling to call and run a threaded loop. 我是c ++和QML的新手,正在努力调用和运行线程循环。 I'd like to add an integer to a QML propery value every x milliseconds. 我想每x毫秒向QML属性值添加一个整数。
I'll omit my main.qml code for now, as I'm able to access the desired property; 我现在将省略main.qml代码,因为我可以访问所需的属性。 this question pertains more to c++. 这个问题更多地与c ++有关。
void fn(QQuickItem x)
{
for (;;)
{
std::this_thread::sleep_for(std::chrono.milliseconds(100));
x->setProperty("value", x->property("value").toReal() + 10);
}
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
//QScopedPointer<TachometerDemo> Tacho(new TachometerDemo);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
QQuickItem *item = engine.rootObjects().at(0)->findChild<QQuickItem*>
("circularGauge");
thread t1(fn, item);
return app.exec();
}
Any guidance on the most efficient means for achieving the above desired functionality would be appreciated. 对于实现上述期望功能的最有效手段的任何指导将被理解。 Whilst I'm currently testing on a win32 platform, a cross-platform approach is required. 虽然我目前正在Win32平台上进行测试,但是需要跨平台的方法。
Better use Qt's event loop mechanism and SIGNAL/SLOTS. 更好地使用Qt的事件循环机制和SIGNAL / SLOTS。 And QThreads if needed. 还有QThreads(如果需要)。 Also if you need to update value in QML in msecconds duration don't do it over setProperty, this function call takes too long. 另外,如果您需要在msecconds持续时间内更新QML中的值,而不要通过setProperty进行更新,则此函数调用会花费很长时间。 You can update your value directly in QML using JS. 您可以使用JS在QML中直接更新您的值。 But if you need to update QML value from C++ you can do it this way: 但是,如果您需要从C ++更新QML值,则可以采用以下方法:
test.h test.h
#include <QObject>
#include <QTimer>
class Test : public QObject
{
Q_OBJECT
public:
Test();
Q_PROPERTY(int value READ value NOTIFY valueChanged)
int value(){return this->m_value;}
signals:
void valueChanged();
private slots:
void timeout();
private:
int m_value;
QTimer * m_timer;
};
test.cpp TEST.CPP
#include "test.h"
Test::Test():m_value(0)
{
this->m_timer = new QTimer(this);
this->m_timer->setInterval(100);
connect(this->m_timer, &QTimer::timeout, this, &Test::timeout);
this->m_timer->start();
}
void Test::timeout()
{
this->m_value += 10;
emit valueChanged();
}
in your main.cpp 在您的main.cpp中
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
Somewhere in your QML: 在您的QML中:
Label
{
text: Test.value
anchors.centerIn: parent
}
This is the fastest way to update QML value from C++ 这是从C ++更新QML值的最快方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.