使用QDialog()实现自定义输入对话框
发布时间:2023-12-16 11:16:29
QDialog类提供了一个基本的对话框窗口,可以用于创建自定义的对话框。可以通过继承QDialog类来创建自定义的输入对话框。在自定义对话框中,可以添加各种输入控件(如QLineEdit、QComboBox等)来让用户输入数据。
下面是一个使用QDialog实现自定义输入对话框的例子:
from PyQt5.QtWidgets import QDialog, QLineEdit, QPushButton, QVBoxLayout, QApplication
class InputDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Input Dialog")
# 创建文本输入框
self.input_line = QLineEdit(self)
# 创建确定按钮
self.ok_button = QPushButton("OK")
self.ok_button.clicked.connect(self.accept)
# 创建布局并添加控件
layout = QVBoxLayout(self)
layout.addWidget(self.input_line)
layout.addWidget(self.ok_button)
def get_input_text(self):
return self.input_line.text()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
dialog = InputDialog()
if dialog.exec_() == QDialog.Accepted:
input_text = dialog.get_input_text()
print("Input text: ", input_text)
sys.exit(app.exec_())
在这个例子中,我们创建了一个名为InputDialog的自定义对话框类,继承自QDialog。在构造函数中,我们添加了一个QLineEdit控件用于输入文本,并创建了一个QPushButton控件用于确定输入。点击确定按钮后,我们使用accept()函数来接受对话框。通过get_input_text()函数,我们可以获取用户输入的文本。
在主程序中,我们创建了一个QApplication对象并实例化了InputDialog对象。然后,我们使用exec_()函数来运行对话框。如果用户点击了确定按钮,我们将获取输入框的文本并打印出来。
通过这个例子,我们可以看到如何使用QDialog来创建自定义的输入对话框,并获取用户输入的文本。你可以根据自己的需要,添加更多的控件来实现更复杂的对话框。希望对你有所帮助!
