我是c ++和QML的新手,我正在努力调用并运行一个线程循环。我想每x毫秒将一个整数添加到QML的值。
我现在省略了main.qml代码,因为我能够访问所需的属性;这个问题更多地涉及到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();
}
对于实现上述所需功能的最有效手段的任何指导将不胜感激。虽然我目前正在win32平台上进行测试,但仍需要跨平台方法。
答案 0 :(得分:2)
更好地使用Qt的事件循环机制和SIGNAL / SLOTS。如果需要,QThreads。此外,如果您需要以毫秒为单位更新QML中的值,请不要在setProperty上执行此操作,此函数调用需要太长时间。您可以使用JS直接在QML中更新您的值。但是如果你需要从C ++更新QML值,你可以这样做:
<强> 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 强>
#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();
}
main.cpp 中的
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
QML中的某个地方:
Label
{
text: Test.value
anchors.centerIn: parent
}
这是从C ++更新QML值的最快方法