PyQt5 组件之QDialog
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PyQt5 组件之QDialog相关的知识,希望对你有一定的参考价值。
QDialog简介
QDialog类的子类主要有QMessageBox,QFileDialog,QColorDialog,QFontDialog,QInputDialog等。
QDialog 常用的方法
方法 | 描述 |
setWindowTitle() | 设置对话框标题 |
setWindowModality() | 设置窗口模态,取值如下 |
Qt.NonModal:非模态,可以和程序的其他窗口进行交互 | |
Qt.WindowModal:窗口模态,程序在未处理玩当前对话框时,将阻止和对话框的父窗口进行交互 | |
Qt.ApplicationModal:应用程序模态,阻止和任何其他窗口进行交互 |
QDialog 效果截图:
PyQt 设计器截图:
*.ui 转换为*.py 代码
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled7.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(270, 110, 160, 80))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.pushButton.setObjectName("pushButton")
# 点击按钮事件,弹出对话框
self.pushButton.clicked.connect(self.showdialog)
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
def showdialog(self):
# 创建QDialog对象
dialog = QDialog()
# 创建按钮到新创建的dialog对象中
btn = QPushButton('ok', dialog)
# 移动按钮,设置dialog的标题
btn.move(50, 50)
dialog.setWindowTitle("Dialog")
# 设置窗口的属性为ApplicationModal模态,用户只有关闭弹窗后,才能关闭主界面
dialog.setWindowModality(Qt.ApplicationModal)
dialog.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
需要向PyUIC 生成的代码,添加如下代码片段:
重点实现QPushButton事件绑定
# 点击按钮事件,弹出对话框
self.pushButton.clicked.connect(self.showdialog)
def showdialog(self):
# 创建QDialog对象
dialog = QDialog()
# 创建按钮到新创建的dialog对象中
btn = QPushButton('ok', dialog)
# 移动按钮,设置dialog的标题
btn.move(50, 50)
dialog.setWindowTitle("Dialog")
# 设置窗口的属性为ApplicationModal模态,用户只有关闭弹窗后,才能关闭主界面
dialog.setWindowModality(Qt.ApplicationModal)
dialog.exec_()
以上是关于PyQt5 组件之QDialog的主要内容,如果未能解决你的问题,请参考以下文章