[英]Is it possible to force execute main thread (GUI thread) from render thread?
[英]Sending parameters from GUI thread to work thread
我在Qt中遇到了一些問題。 我在GUI線程中分配了一些參數:
newton.h(工作線程):
class Newton : public QThread
resic.cpp(GUI線程):
.
.
.
Newton mythread;
resic::resic(QWidget *parent) :
QWidget(parent),
ui(new Ui::resic)
{
ui->setupUi(this);
mythread.start();
}
void resic::on_PushButton_clicked()
{
w1=ui->doubleSpinBox_2->value();
um1=ui->doubleSpinBox->value();
alpha1=ui->doubleSpinBox_3->value();
et01=ui->doubleSpinBox_4->value();
Er1=ui->doubleSpinBox_11->value();
Rx1=ui->doubleSpinBox_12->value();
xa1=ui->doubleSpinBox_8->value();
xb1=ui->doubleSpinBox_9->value();
q1=ui->doubleSpinBox_10->value();
ya1=(q1-2*q1);
yb1=ui->doubleSpinBox_10->value();
maxl1=ui->spinBox->value();
}
我想在單擊按鈕后將這些參數發送到工作線程,然后在該工作線程中運行一些計算。 但是我不知道如何發送參數。 你能給我一些建議嗎?
非常感謝你。
在工作線程中運行一段代碼的簡單解決方案是利用Qt Concurrent框架。 另一種方案是把 該 工人 到 一個QObject
,並使用一個QThread
直接。
struct Parameters {
double w1, um1, alpha1, et01, ...;
};
struct Result {
...
};
Result calculate(const Parameters & p) {
...
}
class resic : public QWidget {
...
QFutureWatcher<Result> m_futureWatcher;
QScopedPointer<Ui::resic> ui;
Q_SLOT void onResults();
...
};
resic::resic(QWidget * parent) : QWidget(parent), ui(new Ui::resic)
{
connect(&m_futureWatcher, SIGNAL(finished()), SLOT(onResults()));
}
resic::~resic() {}
Parameters resic::get()
{
Parameters p;
p.w1=ui->doubleSpinBox_2->value();
p.um1=ui->doubleSpinBox->value();
p.alpha1=ui->doubleSpinBox_3->value();
p.et01=ui->doubleSpinBox_4->value();
...
return p;
}
void resic::on_PushButton_clicked()
{
Parameters const p(get());
QFuture<Result> future = QtConcurrent::run(&calculate);
m_futureWatcher.setFuture(future);
}
void resic::onResults()
{
Result const r = m_futureWatcher.result();
...
}
重要的是要記住, QThread
對象通常位於創建它的線程中,而不是它管理的線程中。 這個經常被忽略的細節意味着QThread
的插槽將在其主線程的上下文中執行,而不是在其管理的線程的上下文中執行。 因此,不建議在QThread
子類中實現新插槽。
您可以從QObject
繼承類“ Newton”,在堆上創建該類的對象並將其移動到新線程。
可以這樣完成:
mythread = new Newton();
QThread * th = new QThread();
mythread->moveToThread(th);
QObject::connect(th,SIGNAL(started()),mythread,SLOT(OnStarted()));
QObject::connect(th,SIGNAL(finished()),mythread,SLOT(OnFinished()));
th->start();
Newton
類中的初始化和終止任務應分別在OnStarted()
和OnFinished()
插槽中完成。
現在,您可以在工作線程中實現一個用於運行計算的插槽。 您可以將GUI線程中的信號連接到包含您要發送的參數的插槽。 當沿着自變量發出該信號時,工作線程中的計算槽從適當的自變量開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.