PyQt5最全89 信号与槽之多窗口交互(1):不使用信号与槽
from PyQt5.QtWidgets import *
import sys
from DateDialog1 import DateDialog1
class MultiWindow1(QWidget):
"""
多窗口交互(1):不使用信号与槽
Win1
强耦合的方式直接从Win2中获取控件得到值
Win2
实现了在两个按钮下调用Win2中的类中的日历控件,也就是在点击按钮1和2对应的槽函数中调用
"""
def __init__(self):
super(MultiWindow1, self).__init__()
self.setWindowTitle('多窗口交互(1):不使用信号与槽')
self.lineEdit = QLineEdit(self)
self.button1 = QPushButton('弹出对话框1')
self.button1.clicked.connect(self.onButton1Click)
self.button2 = QPushButton('弹出对话框2')
self.button2.clicked.connect(self.onButton2Click)
gridLayout = QGridLayout()
gridLayout.addWidget(self.lineEdit)
gridLayout.addWidget(self.button1)
gridLayout.addWidget(self.button2)
self.setLayout(gridLayout)
def onButton1Click(self):
dialog = DateDialog1(self)
# result = dialog.exec()
date = dialog.dateTime()
self.lineEdit.setText(date.date().toString())
dialog.destroy()
def onButton2Click(self):
date, time, result = DateDialog1.getDateTime()
self.lineEdit.setText(date.toString())
if result == QDialog.Accepted:
print('点击确定按钮')
else:
print('点击取消按钮')
if __name__ == '__main__':
app = QApplication(sys.argv)
example = MultiWindow1()
print(example.__doc__)
example.show()
sys.exit(app.exec_())
下面是对应的DateDialog1 文件
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class DateDialog1(QDialog):
def __init__(self, parent=None):
super(DateDialog1, self).__init__(parent)
self.setWindowTitle('DateDialog')
layout = QVBoxLayout(self)
self.datetime = QDateTimeEdit(self)
# 弹出的
self.datetime.setCalendarPopup(True)
self.datetime.setDateTime(QDateTime.currentDateTime())
layout.addWidget(self.datetime)
# 按钮盒子
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def dateTime(self):
return self.datetime.dateTime()
@staticmethod # 静态方法是无法访问实例变量的
def getDateTime(parent=None):
dialog = DateDialog1(parent)
result = dialog.exec()
date = dialog.dateTime()
return date.date(), date.time(), result == QDialog.Accepted
结果
点击弹出对话框1,调用onButton1Click槽函数。在实例化DateDialog1类以后,调用实例化对象下的QDateTimeEdit方法,其实也就是直接实例化QDateTimeEdit控件也一样的,然后设置文本框的内容。结果如下
点击弹出对话框2,弹出
额外补充一点,在多窗口交互时,有两种使用情景,可以复制、粘贴使用的
第一种:
def ***(self):
self.detect = DectectWindow()
# self.hide() # 隐藏当前窗口
self.detect.show()
这就是直接调用了,上边可以是槽函数,也可以是方法。
第二种:
def ***(self):
self.form = QWidget()
self.detect = Ui_Form()
self.detect.setupUi(self.form)
self.form.show()
这种模式适用于使用Qt Designer生成的代码,复制的请点个赞吧!