QT 在 线程里QGraphicsView 不能实时显示图片
时间: 2023-08-26 15:09:18 浏览: 116
在Qt中,图形视图(QGraphicsView)是一个 QWidget 子类,它用于显示和编辑2D图形项。当您将 QGraphicsView 放置在单独的线程中时,您需要确保在主线程中更新场景。这是因为 Qt 图形系统本质上是单线程的,即只有在主线程中才能进行 GUI 更新。
您可以使用信号和槽机制将图像传递到主线程并更新场景。具体来说,您可以在子线程中发出一个信号,当信号在主线程中接收到时,您可以将图像添加到场景中并更新 QGraphicsView。以下是一个示例代码:
```
class MyThread : public QThread
{
Q_OBJECT
signals:
void sendImage(QImage image);
protected:
void run() override {
// Load image in this thread
QImage image("image.jpg");
emit sendImage(image);
}
};
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
// Create QGraphicsView and QGraphicsScene
view = new QGraphicsView(this);
scene = new QGraphicsScene(this);
view->setScene(scene);
// Connect signal to slot
connect(this, &MyWidget::imageReceived, this, &MyWidget::updateScene);
}
private slots:
void updateScene(QImage image) {
// Add image to scene and update view
QPixmap pixmap = QPixmap::fromImage(image);
scene->addPixmap(pixmap);
view->fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
}
private:
QGraphicsView *view;
QGraphicsScene *scene;
signals:
void imageReceived(QImage image);
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWidget w;
w.show();
// Start worker thread
MyThread thread;
thread.start();
// Connect thread signal to widget slot
QObject::connect(&thread, &MyThread::sendImage, &w, &MyWidget::imageReceived);
return a.exec();
}
```
在上面的示例中,MyThread 类表示子线程,它加载图像并将其发送到主线程。MyWidget 类是一个 QWidget 子类,它包含 QGraphicsView 和 QGraphicsScene。它还具有一个名为 imageReceived 的槽,用于将接收到的图像添加到场景中并更新 QGraphicsView。在 main() 函数中,我们创建了 MyWidget 实例,并启动了 MyThread 实例。我们还使用 connect() 函数将 MyThread 的 sendImage 信号连接到 MyWidget 的 imageReceived 槽。
请注意,如果您频繁地向 QGraphicsView 添加图形项,则可能会降低性能。在这种情况下,您可以考虑仅在图像发生更改时更新 QGraphicsView。