以下是一个示例代码,展示了如何使用对话框以及从不同文件重用对话框:
在主文件中,我们创建一个自定义对话框类 DialogClass,并在其中定义一个打开对话框的方法 openDialog:
# main.py
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton
from dialog import DialogClass
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.button = QPushButton('Open Dialog', self)
self.button.clicked.connect(self.openDialog)
def openDialog(self):
dialog = DialogClass(self)
dialog.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
然后,在另一个文件 dialog.py 中,我们定义了 DialogClass 的具体实现:
# dialog.py
from PyQt5.QtWidgets import QDialog, QLabel, QVBoxLayout
class DialogClass(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
layout = QVBoxLayout()
label = QLabel('This is a dialog', self)
layout.addWidget(label)
self.setLayout(layout)
在主文件中,我们创建了一个主窗口 MainWindow,并在其中添加了一个按钮。当按钮被点击时,我们会创建一个 DialogClass 的实例,并调用 exec_() 方法显示对话框。
在 dialog.py 文件中,我们创建了一个 DialogClass 类,继承自 QDialog 类,定义了一个简单的对话框布局,并将其显示出来。
这样,我们可以在主窗口中打开对话框,并在对话框中展示内容。我们也可以在其他文件中重用 DialogClass 类,只需导入 dialog.py 文件,并创建一个 DialogClass 的实例即可。