- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 QtConcurrent::run 在我的 MainWindow 类中执行一个函数,以便 UI 在计算期间保持响应。以下是我的实现方式:
void MainWindow::on_calculate_pb_clicked()
{
QFuture<void> future = QtConcurrent::run(this,&MainWindow::calculation);
}
void MainWindow::calculation()
{
progressBar->show();
loadMap();
integral.clear();
positions.clear();
offset.clear();
lines = 0;
for(int i=0;i<paths.size();i++)
{
if(i ==0)
{
lines = countNumberOfLines(paths.at(i));
}
double file = i+1;
ui->statusBar->showMessage(QString("Processing file %1 of %2").arg(file).arg(paths.size()));
calculateIntegral(paths.at(i));
offset.push_back(ui->tableWidget->item(i,1)->text().toDouble());
}
makePositionVector();
plotData(ui->customPlot);
ui->export_pb->setEnabled(true);
progressBar->hide();
ui->statusBar->showMessage("Done",3000);
}
void MainWindow::calculateIntegral(QString path)
{
QVector<double> mappeddata,tempdata;
mappeddata.resize(map.size());
tempdata.resize(numberofdetectors);
double currentLine = 0;
QFile File(path);
if(File.exists()==true){
File.open(QIODevice::ReadOnly);
QTextStream in(&File);
double val;
while(!in.atEnd())
{
for(int j = 0;j<numberofdetectors;j++)
{
in >> val;
tempdata[j]+=val;
currentLine++;
double progress = currentLine/lines*100;
progressBar->setValue(progress);
}
}
for(int i =0;i<map.size();i++)
{
mappeddata[i] = tempdata.at(map.at(i));
}
for(int k = 0;k<numberofdetectors; k++)
{
integral.push_back(mappeddata.at(k));
}
}
File.close();
}
它工作正常,用户界面响应迅速,进度条更新正确,但是在输出中我多次收到错误“QObject::setParent:无法设置父级,新父级在不同的线程中”循环执行。
知道是什么原因造成的,或者对更好地实现 QtConcurrent::run 有什么建议吗?
谢谢
最佳答案
您不能从工作线程中接触任何 Qt 提供的 QWidget
对象,因为它们的大多数方法都不是线程安全的。
相反,解决此问题的一种方法是在 worker 中进行计算,然后将更新状态的仿函数提交到主线程。参见 this answer了解详情。
您的代码将变为:
void MainWindow::calculation()
{
postToThread([this]{ progressBar->show(); });
loadMap();
integral.clear();
positions.clear();
offset.clear();
lines = 0;
for(int i=0;i<paths.size();i++)
{
if (i == 0)
lines = countNumberOfLines(paths.at(i));
auto file = i+1;
postToThread([this]{
ui->statusBar->showMessage(
tr("Processing file %1 of %2").arg(file).arg(paths.size()));
});
calculateIntegral(paths.at(i));
postToThread([this]{
offset.push_back(ui->tableWidget->item(i,1)->text().toDouble());
});
}
makePositionVector();
postToThread([this]{
plotData(ui->customPlot);
ui->export_pb->setEnabled(true);
progressBar->hide();
ui->statusBar->showMessage("Done",3000);
});
}
以类似的方式修改 calculateIntegral
,但请确保您不会过于频繁地发出进度更新。
还要确保 UI 代码不会在其他地方访问您从 worker 更新的成员。这可能很难,因为您混合了 UI 和计算。相反,将 worker 抽象为没有 UI 的 QObject
,并通过指示进度/状态的信号将其连接到其他代码。您仍将在该对象中使用 QtConcurrent::run
,但确保没有其他线程访问该对象的私有(private)状态变得更简单。
要将完成的结果从 worker 仿函数中推出,您可以发出一个包含结果的信号。 Data
类型的复制成本应该很低,例如您可以使用 QSharedData
/QSharedDataPointer
来实现它。或者您可以通过 QSharedPointer
保存它。
class Computation : public QObject {
Q_OBJECT
void work() {
Data data;
... // updates data
emit finished(data);
}
public:
Q_SLOT void compute() {
QtConcurrent::run(&Worker::work, this);
}
Q_SIGNAL void finished(Data data);
};
您还可以将结果存储在对象中,并注意在计算处于事件状态时不会访问它们:
class Computation : public QObject {
Q_OBJECT
bool m_active { false };
Data m_data;
void work() {
... // updates m_data
m_active = false;
}
public:
Q_SLOT void compute() {
m_active = true;
QtConcurrent::run(&Worker::work, this);
}
const Data & data() const {
Q_ASSERT(! m_active);
return m_data;
}
};
当然,如果您在主线程中存储对 data()
的引用,然后调用 compute()
,您将有未定义的行为,所以不要不要那样做。
如果任何数据类型是隐式共享容器,如 QVector
或 QString
,您应该按值返回它们,并且任何访问都是线程安全的:
QVector<MyData> data() const {
Q_ASSERT(! m_active);
return m_data;
}
请注意,QFile
是一个正确的 C++ 类。当它被破坏时,它会释放持有的任何资源。手动关闭文件是不必要的:编译器应该在这里帮助你,这就是 C++ 对象模型与例如Java 的。
关于c++ - QtConcurrent::run with MainWindow 函数,警告消息 "QObject::setParent: Cannot set parent, new parent is in a different thread",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523509/
以下是我遇到的编译错误: /usr/lib/qt-3.3/include/qobject.h: In copy constructor Product::Product(const Product&)
class CHIProjectData : public QObject { public: CHIProjectData(); CHIProjectData(QMap aProje
这个问题在这里已经有了答案: Could I have copy constructor for subclass of QObject? (3 个答案) 关闭 7 年前。 我收到错误: C:\Qt
将一个项目从 Qt4 迁移到 Qt5 我得到了这个错误,我已经研究过,显然你不能从 QObject 创建一个派生类的复制构造函数(这太不可思议了,因为这段代码不是我的,它应该在以前的版本中编译).复制
我试图返回一个派生自 QObject 的类,但出现以下错误 Error : 'QObject::QObject' : cannot access private member declared in
我正在编写一些派生自 QObject 的 Qt 类,它看起来像: class A : public QObject { Q_OBJECT public: A() : QObject() {}
考虑以下代码: #include class A : public QObject { Q_OBJECT public: A(QObject* parent = 0)
我似乎需要 QObject 类型的 p 实例,我已经扩展了 QObject 并在 fileprocessor.h 中定义了关键字 Q_OBJECT,我不确定我还能做什么。 -文件处理器.h #ifnd
我有一个继承 QObject 的类 BatchItem,还有几个继承自 BatchItem 的类: #ifndef BATCHITEM_H #define BATCHITEM_H #include
这是代码: void invokeQMLFunction2Arg(QObject * object, QString func, QVariant p1, QVariant p2) { QMe
我读过 documentation对于 QObject::connect(对于 Qt 5.4),但我对重载有疑问 QMetaObject::Connection QObject::connect(co
我最近一直在使用QTCreator,我爱上了ATM。不幸的是,我想将它与 Python 一起使用,但我遇到了问题。我遇到的最大问题是发现我的应用程序上下文的子级返回 None。 main.py imp
使用 #include 有什么区别吗?和 #include ? 这两个似乎都有效,所以必须有一些原因来说明为什么 #include是首选吗? 最佳答案 任何不带 .h 扩展名的标准 Qt 头文件都保证
我写的Python代码看起来像这样: class Regularblock(QGraphicsItem): def __init__(self): super(QGraphic
Qt 框架有一个 signal for all QObjects which is emmited before destruction那个QObject。此事件可用于在它指向的对象被销毁时自动清空一
我想创建 SerialPort 类,它可以自动接收消息,然后发出信号。 但是当我编译它时显示错误信息: error: 'QObject' is an ambiguous base of 'Serial
(C++/Qt) 我有一个指向 QObject 的智能指针。让我们说一个 QWeakPointer。由于某些外部原因(可能发生在另一个对象中或由于某个事件),指向的对象可能会被销毁。因为我有一个智能指
QObject 析构函数的 Qt 引用说: 进出该对象的所有信号都会自动断开,该对象的任何未决发布事件都会从事件队列中删除。但是,使用 deleteLater() 通常比删除更安全直接一个 QObje
您好,我需要从后台进行一些套接字通信,我为此使用了QtConcurrent::run,但给了我警告。 QObject: Cannot create children for a parent that
如何打破 QObject 的父子所有权?似乎不再有明确的方法来做到这一点。打电话就够了 QObject::setParent(NULL) 最佳答案 你是对的。制作 QObject一个孤儿,简单地做 /
我是一名优秀的程序员,十分优秀!