我正在编写一个Windows Visual Studio 2017 C ++程序,它将一系列帧从捕获卡渲染到Qt 5.9 OpenGL窗口。加载和处理图像是在一个线程中异步完成的,直到它停止:
void readFile(std::string filename)
{
auto reader = openreader(file);
while(!done())
{
QImage frame = reader.read();
processFrame(frame);
displayFrame(frame); /// <--- here
}
并且线程可能会被
踢掉std::thread workit(readfile,"c:\funtimes.dat");
在屏幕上显示包含QImage frame
像素的正确模式是什么?在.Net中,必须注意只修改主线程中的gui。这对Qt有什么作用?
我目前的方法是将局部变量设置为等于帧的副本,然后在OpenGL QWidget上调用Update()
。也就是说,代码displayFrame
看起来像:
void displayFrame(QImage frame)
{
// Mutex here
oglWindow.copyOfFrame= frame.copy();
oglWindow.update();
}
这会触发使用
绘制到窗口的paintEvent
painter.drawImage(QPoint(width()/2 - bi.width()/2, height()/2 - bi.height()/2), copyOfFrame);
当主窗口消息泵外部的线程正在触发更新或是否需要其他机制时,这是否安全且合适?
答案 0 :(得分:1)
如果异步图像加载器是QThread的子类,则可以从图像加载器发出主线程信号,QT将确保在主线程中执行处理代码槽。请参阅Qt Threads and QObjects doc
如果图像加载器不是QThread,只是常规的Win32线程,则应使用QCoreApplication :: PostEvent进行线程安全交付