下面的代码创建了一个带有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_()
请您参考如下方法:
您可以从对话中发送信号并在另一个对话中捕获它。
在发射对话框中定义一个信号,使用pyqtSignal :
class Modal(QDialog):
confirmed = pyqtSignal(str)
# ...
该信号有一个类型为 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
要捕获信号,其他类需要一个插槽:
class Dialog(QDialog):
# ...
def changeText(self, t):
self.label.setText(t)
插槽函数将在其 t 参数中接收文本,并相应地设置标签文本,但要实现这一点,信号和插槽必须连接。
首先,让我们编辑 Modal 类构造函数,并删除最后两行:
self.setModal(True)
self.show()
让我们在 Dialog 的 showModal 中使用它们,连接 changeText 插槽和 Modal 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()
