POQ*_*vid 1 c++ qt multithreading openmp
在尝试了解我所知道的一切之后,甚至通过添加
QT_MainWindow::QT_MainWindow(QWidget *parent) :QMainWindow(parent), ui(new Ui::QT_MainWindow)
{
ui->setupUi(this);
qRegisterMetaType<QTextCursor>("QTextCursor");
qRegisterMetaType<QTextBlock>("QTextBlock");
}
Run Code Online (Sandbox Code Playgroud)
对于我的源代码,我仍然无法修改QTextEdit和QPlainTextEdit中其他线程的文本,我也在使用OpenMP和Qt.
任何人都可以告诉我从QTextEdit和QPlainTextEdit中的其他线程修改文本的正确方法是什么,因为我没有找到任何关于它的帮助我
这是我的来源:
void QT_MainWindow::Load()
{
ui->QT_PlainTextEdit->setPlainText("");
std::ifstream file("File.txt");
std::string line;
#pragma omp parallel
{
while ( std::getline(file, line) )
ui->QT_PlainTextEdit->appendPlainText( QString::fromStdString(line));
file.close();
}
}
Run Code Online (Sandbox Code Playgroud)
我设法让它像这样工作
void QT_MainWindow::Load()
{
omp_set_dynamic(0);
omp_set_nested(3);
#pragma omp parallel num_threads(3)
{
ui->QT_PlainTextEdit->setPlainText("");
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试设置文本
void QT_MainWindow::Load()
{
omp_set_dynamic(0);
omp_set_nested(3);
#pragma omp parallel num_threads(3)
{
ui->QT_PlainTextEdit->setPlainText("TEST");
}
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x3bbc758), parent's thread is QThread(0x3bd140), current thread is QThread(0x3bbcb68)
The program has unexpectedly finished.
Run Code Online (Sandbox Code Playgroud)
也
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x465bfc0), parent's thread is QThread(0x3f3ad60), current thread is QThread(0x466d450)QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x465bfc0), parent's thread is QThread(0x3f3ad60), current thread is QThread(0x46eebe0)HEAP[app.exe]:
Invalid address specified to RtlFreeHeap( 00000000023F0000, 0000000003F3DC40 )
Run Code Online (Sandbox Code Playgroud)
问题是您正在主线程以外的线程中访问Qt GUI对象.
来自http://doc.qt.io/qt-4.8/threads-qobject.html
尽管QObject是可重入的,但GUI类(尤其是QWidget及其所有子类)不可重入.它们只能在主线程中使用.
解决这个问题的一种方法是使用Qt信号/插槽使用QueuedConnection将工作线程中的信号连接到主线程中的插槽,但在您的情况下,我认为这没有多大意义.即使您获得了使用openmp的信号,您也无法以与QPlainTextEdit并行的方式追加字符串,从而提高性能.