首页 > 解决方案 > PyQt5 在单线程上连续运行多线程进程

问题描述

我正在使用 PyQT5 中的一个应用程序,它的两侧有两个底座,中间有一个 OCC 3d 查看器和一个 TextEdit。OCC 查看器的 .ExportToImage() 方法允许截取查看器的屏幕截图。但是由于应用程序具有响应式设计,因此查看器的大小被调整为很薄(在某些显示分辨率上),因此屏幕截图也很薄。

图形用户界面

小分辨率的 3d 查看器的屏幕截图

我试图将窗口调整为特定大小,然后隐藏除 3D 查看器之外的所有内容。这会放大查看器,从而节省裁剪的屏幕截图。但是当我隐藏并调整大小然后截图时,截图仍然很薄。这是代码:

def take_screenshot(self):
 Ww=self.frameGeometry().width()                   
 Wh=self.frameGeometry().height()
 self.resize(700,500)
 self.outputDock.hide() #Dock on the right
 self.inputDock.hide()  #Dock on the left
 self.textEdit.hide()   #TextEdit on the Bottom-Middle
 self.display.ExportToImage(fName)   #Display is the 3d Viewer's display on the Top-Middle
 self.resize(Ww,Wh)
 self.outputDock.show()
 self.inputDock.show()
 self.textEdit.show()

我猜这是因为 PyQt5 的上述 .show()、.hide()、.resize() 方法是多线程的,一旦我运行它们,它们就不会连续运行而是并行运行。因此,屏幕截图是在其他进程完成之前拍摄的。

有没有办法解决这个问题?或者,还有更好的方法?

标签: python-3.xpyqt5

解决方案


没有多线程。事件是循环处理的,所以称为eventloop。

尝试这个:

def take_screenshot(self):
    Ww=self.frameGeometry().width()                   
    Wh=self.frameGeometry().height()
    self.resize(700,500)
    self.outputDock.hide() #Dock on the right
    self.inputDock.hide()  #Dock on the left
    self.textEdit.hide()   #TextEdit on the Bottom-Middle
    QTimer.singleShot(0, self._capture)

def _capture(self):
    # app.processEvents()  # open this line if it still doesn't work, I don't know why.
    self.display.ExportToImage(fName)   #Display is the 3d Viewer's display on the Top-Middle
    self.resize(Ww,Wh)
    self.outputDock.show()
    self.inputDock.show()
    self.textEdit.show()

推荐阅读