这是我的代码:
from PySide.QtGui import *
class window_A(QWidget):
def __init__(self):
super(window_A, self).__init__()
layout = QVBoxLayout() # Create horisontal layout
self.setLayout(layout) # Use horisontal layout to place widgets in window
self.resize(300,50) # resize window
self.button_A = QPushButton('PRESS')
self.button_A.clicked.connect(self.func)
self.button_A.clicked.connect(self.close)
layout.addWidget(self.button_A)
def func(self):
print 'A'
app = QApplication([])
print 'BEFORE'
widget = window_A()
widget.show()
print 'AFTER'
app.exec_()
在显示窗口之后直到用户按下按钮后,如何保持代码的执行?例如。仅在按下按钮并关闭窗口之后才打印“ AFTER”。
答案 0 :(得分:2)
在这种情况下,为了防止同步执行继续进行,您可以使用QEventLoop,并可以通过在closeEvent中发出一个信号来通知窗口是否关闭:
from PySide import QtCore, QtGui
class Window_A(QtGui.QWidget):
closed = QtCore.Signal()
def __init__(self):
super(Window_A, self).__init__()
layout = QtGui.QVBoxLayout(self)
self.resize(300, 50)
self.button_A = QtGui.QPushButton("PRESS")
self.button_A.clicked.connect(self.func)
self.button_A.clicked.connect(self.close)
layout.addWidget(self.button_A)
@QtCore.Slot()
def func(self):
print("A")
def closeEvent(self, event):
super(Window_A, self).closeEvent(event)
self.closed.emit()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
print("BEFORE")
widget = Window_A()
widget.show()
loop = QtCore.QEventLoop()
widget.closed.connect(loop.quit)
loop.exec_()
print("AFTER")
答案 1 :(得分:0)
我有解决办法!需要将QWidget
更改为QDialog
,将show
更改为exec_()
:
from PySide.QtGui import *
class window_A(QDialog):
def __init__(self):
super(window_A, self).__init__()
layout = QVBoxLayout() # Create horisontal layout
self.setLayout(layout) # Use horisontal layout to place widgets in window
self.resize(300,50) # resize window
self.button_A = QPushButton('PRESS')
self.button_A.clicked.connect(self.func)
self.button_A.clicked.connect(self.close)
layout.addWidget(self.button_A)
def func(self):
print 'A'
self.done(256)
app = QApplication([])
print 'BEFORE'
widget = window_A()
if widget.exec_() == 256:
print 'AFTER'
app.exec_()