【发布时间】:2020-07-15 07:42:07
【问题描述】:
我正在通过 QT 制作一些 GUI。 我几乎完成了我的工作,但我很难处理 Qthread。 我的目标是测量电机的位置(它移动)并将其显示在 Qtextbrowser 上,同时在主线程中运行另一个函数。当我写下面这样的代码时,人们说我不能直接在线程中使用 QTextBrowser(Qwidget),所以我正在寻找如何将位置值返回给主线程。能帮我一下吗? MDCE 是另一个标题中的一个类,我附加的代码是我的第一个代码的一些部分。
void MotorPort::StartThread(MDCE* com, QTextBrowser* browser)
{
thread1 = QThread::create(std::bind(&MotorPort::MeasureLocation,this,com,browser));
thread1 -> start();
}
void MotorPort::MeasureLocation(MDCE* com, QTextBrowser* browser)
{
double location;
while(1)
{
location = CurrentLocation(com); \\return current position value
browser->setText(QString::number(location));
if (QThread::currentThread()->isInterruptionRequested()) return ;
}
}
void MotorPort::stopMeasure()
{
thread1->requestInterruption();
if (!thread1->wait(3000))
{
thread1->terminate();
thread1->wait();
}
thread1 = nullptr;
}
【问题讨论】:
-
您可能无法从其他线程访问 GUI 内容。 Qt 小部件不是线程安全的。我在对SO: How to alter Qt Widgets in WINAPI threads? 的回答中写了一些关于这个主题的内容(忽略了问题的 Windows 特定方面)。
标签: qt user-interface qwidget qthread