需求:
在PYQT5中,点击主窗口中的按钮,弹出子窗口。
测试代码:
例1:
在主窗口添加按钮,并把按钮信号关联槽,在槽函数中创建子窗口对象赋值到普通变量,并调用其 show 方法。
from PyQt5.QtWidgets import *
import sys
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("主窗口")
button = QPushButton("弹出子窗", self)
button.clicked.connect(self.show_child)
def show_child(self):
child_window = Child()
child_window.show()
class Child(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("我是子窗口啊")
# 运行主窗口
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
运行结果: 该段代码运行后,点击主窗口中的按钮,子窗口一闪而过。
例2:
在主窗口添加按钮,并把按钮信号关联槽,在槽函数中创建子窗口对象并赋值为对象属性,并调用其 show 方法。