gpt4 book ai didi

QThread 不能正常工作

转载 作者:行者123 更新时间:2023-12-04 12:41:42 27 4
gpt4 key购买 nike

这是 QTread 的子对象...并在主线程中将其具体化....

运行时错误如下:

ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 176f0a8. Receiver '' (of type 'MainWindow') was created in thread 3976a0", file c:\ndk_buildrepos\qt-desktop\src\corelib\kernel\qcoreapplication.cpp, line 405 Invalid parameter passed to C runtime function. Invalid parameter passed to C runtime function.

class PaintThread : public QThread {

private:
QWidget* parent;

public:
~PaintThread() {}

PaintThread(QWidget* parent = 0) {
this->parent = parent;
}

void run() {
while (1) {
this->msleep(5000);
parent->repaint();
}
this->exec();
}
};

这是 MainFrame 的构造函数:

MainWindow::MainWindow(QWidget *parent) :
QWidget(parent)
{
tankPoint = new QRect(50, 50, 30, 30);

this->show();

PaintThread * pt = new PaintThread(this);
pt->start();
}

下面是MainWindow的覆盖paintEvent

void paintEvent(QPaintEvent*) {
QPainter p(this);

p.setPen(Qt::red);
p.setBrush(Qt::red);
p.drawEllipse(*tankPoint);

tankPoint->setLeft(200);
}

谁能告诉我为什么?

最佳答案

父级(在本例中是您的 MainWindow)位于不同的线程中。根据 Qt 文档

You can manually post events to any object in any thread at any time using the thread-safe function QCoreApplication::postEvent(). The events will automatically be dispatched by the event loop of the thread where the object was created. Event filters are supported in all threads, with the restriction that the monitoring object must live in the same thread as the monitored object. Similarly, QCoreApplication::sendEvent() (unlike postEvent()) can only be used to dispatch events to objects living in the thread from which the function is called.

因此,作为解决方案,我提出以下建议:

  • 在您的 PaintThread 类中定义一个信号
  • 将此信号连接到 QWidget 子类中的 paint() 槽
  • 在 run() 函数中发出它

关于QThread 不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9018434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com