(这是几天前问题的后续跟进。我无法确定哪个是最好的 - 编辑原始问题,跟进评论或发布新问题。我去了最后......)
之前,我发布了一个关于PyQt退出[PyQt app crashes on exit (Python 3.4.3 / PyQt5 / Windows 10)时崩溃的应用程序,我发现这是一个相当常见的问题。有人建议我尝试提供MCVE。这是我能把它缩小的最小值:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# ======================================================================
# | Class: Form
# |
# |
# ======================================================================
class FormWidget(QWidget):
def __init__(self, parent):
super(FormWidget, self).__init__(parent)
# Initializations
self.initForm()
# ------------------------------------------------------------------
# | initForm()
# |
# | Create new form object
# ------------------------------------------------------------------
def initForm(self):
# Main horizontal layout
self.hlayout = QHBoxLayout()
# Left vertical layout -- image view and display
self.left_vlayout = QVBoxLayout()
self.image = QGraphicsPixmapItem(QPixmap("Audubon.jpg"))
self.image.setScale(2.0)
self.scene = QGraphicsScene()
self.scene.addItem(self.image)
self.view = QGraphicsView(self.scene)
self.left_vlayout.addWidget(self.view)
self.display = QLabel() # [1]
self.left_vlayout.addWidget(self.display) #
# Right vertical layout -- name edit, movement controls
self.right_vlayout = QVBoxLayout()
self.name = QLineEdit()
self.right_vlayout.addWidget(self.name)
self.controls_layout = QGridLayout() # [2]
self.right_vlayout.addLayout(self.controls_layout) #
# Add left and right vertical layouts to horizontal layout, and set it for form
self.hlayout.addLayout(self.left_vlayout)
self.hlayout.addLayout(self.right_vlayout)
self.setLayout(self.hlayout)
# ------------------------------------------------------------------
# | keyPressEvent()
# |
# | Process keyboard input
# ------------------------------------------------------------------
def keyPressEvent(self, event):
key = event.key()
mod = int(event.modifiers()) # [3]
if key == Qt.Key_Q:
mainWindow.close()
# ======================================================================
# | Class: MainWindow
# |
# |
# ======================================================================
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
form = FormWidget(self)
self.setCentralWidget(form)
self.resize(1750, 700)
self.move(50, 300)
# ======================================================================
# | Main
# |
# |
# ======================================================================
if __name__ == '__main__':
import sys
import time
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.setWindowTitle("MCVE")
mainWindow.show()
sys.exit(app.exec_())
使用名为AutoIt的工具,我编写了一个自动化脚本来测试代码。该脚本运行代码100次,每次启动它,然后立即传递一个' q'退出的角色。
如上所示,代码在退出时总会崩溃,有时会在100次运行中(通常在前十二次或两次内)。
如果我做出任何这些更改(单独,不是一次性完成):
然后代码连续运行100次,而不会在退出时崩溃。
我对代码很仔细,但我看不出有什么不对劲。特别是,我看不出有关这三组代码的任何特殊内容,这些代码在被注释掉时会使其正常运行。
有什么想法吗?
再次感谢。 /约翰