alp*_*ric 2 python qt dialog pyqt
下面的代码创建一个带有QLabel和单个 的对话框窗口QPushButton。单击该按钮将弹出第二个对话框,其中包含文本字段和Confirm按钮。用户在文本字段中输入文本并单击“确认”按钮。第二个对话框关闭,返回用户输入的文本。返回时,第一个对话框使用它来替换标签的“默认文本值”。
如何将用户文本值传递到第一个对话框?
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
app = QApplication([])
class Modal(QDialog):
def __init__(self, parent):
super(Modal, self).__init__(parent)
self.setLayout(QVBoxLayout())
self.lineedit = QLineEdit(self)
self.layout().addWidget(self.lineedit)
button = QPushButton(self)
button.setText('Confirm')
button.clicked.connect(self.close)
self.layout().addWidget(button)
self.setModal(True)
self.show()
class Dialog(QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setLayout(QVBoxLayout())
button = QPushButton('Show modal dialog')
button.clicked.connect(self.showModal)
self.label = QLabel('Default text value')
self.layout().addWidget(self.label)
self.layout().addWidget(button)
self.resize(200, 50)
self.show()
def showModal(self):
dialog = Modal(self)
dialog = Dialog()
app.exec_()
Run Code Online (Sandbox Code Playgroud)
您可以从一个对话框发送信号并在另一个对话框中捕获它。
使用pyqtSignal在发出对话框中定义信号:
class Modal(QDialog):
confirmed = pyqtSignal(str)
# ...
Run Code Online (Sandbox Code Playgroud)
该信号具有一个类型参数str,将从插槽中发出confirm,从行编辑用户输入的文本读取后:
def confirm(self):
self.close()
value = self.lineedit.text()
print ('entered value: %s' % value)
self.confirmed.emit(value) #emit the signal, passing the text as its only argument
Run Code Online (Sandbox Code Playgroud)
为了捕获信号,另一个类需要一个槽:
class Dialog(QDialog):
# ...
def changeText(self, t):
self.label.setText(t)
Run Code Online (Sandbox Code Playgroud)
槽函数将接收其参数中的文本t,并相应地设置标签文本,但要发生这种情况,信号和槽必须连接。
首先,让我们编辑Modal类构造函数,并删除最后两行:
self.setModal(True)
self.show()
Run Code Online (Sandbox Code Playgroud)
连接插槽和信号后,让我们在Dialogs中使用它们:showModalchangeTextModal confirmed
def showModal(self):
modal_dialog = Modal(self)
modal_dialog.confirmed.connect(self.changeText) #connect signal and slot
modal_dialog.setModal(True)
modal_dialog.show()
Run Code Online (Sandbox Code Playgroud)
完整参考:信号和槽的支持