欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python之PyQt6對(duì)話框的實(shí)現(xiàn)

 更新時(shí)間:2023年01月16日 17:23:13   作者:魚(yú)聽(tīng)禪  
這篇文章主要介紹了Python之PyQt6對(duì)話框的實(shí)現(xiàn),文章內(nèi)容詳細(xì),簡(jiǎn)單易懂,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

對(duì)話框是界面編程中重要的窗體,一般用于提示或者一些其他特定操作。

使用QDialog顯示通用消息框

直接使用QDialog類,可以及通過(guò)對(duì)話框進(jìn)行通用對(duì)話框顯示,亦可以通過(guò)自定義設(shè)置自己需要的對(duì)話框。

# _*_ coding:utf-8 _*_
 
import sys
 
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QVBoxLayout
from PyQt6.QtWidgets import QHBoxLayout
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QDialog
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
 
 
class MainWindowView(QMainWindow):
    """主窗體界面"""
 
    def __init__(self):
        """構(gòu)造函數(shù)"""
        super().__init__()
 
        self.setWindowTitle("MainWindow")
        self.setWindowIcon(QIcon(r"./res/folder_pictures.ico"))
        self.resize(300, 200)
        self.setMinimumSize(600, 400)
 
 
        self.center()
        self.initui()
 
        
 
    def initui(self):
        """初始函數(shù)"""
 
        self.vboxlayout = QVBoxLayout(self)
        self.main_widget = QWidget()
        self.main_widget.setLayout(self.vboxlayout)
        self.setCentralWidget(self.main_widget)
 
        self.hboxlayout = QHBoxLayout(self)
        self.btn = QPushButton(self)
        self.btn.setText("彈出對(duì)話框")
        self.btn.move(100,100)
        self.btn.clicked.connect(self.show_dialog)
 
    def center(self):
        """居中顯示"""
        win_rect = self.frameGeometry()  # 獲取窗口矩形
        screen_center = self.screen().availableGeometry().center()  # 屏幕中心
        win_rect.moveCenter(screen_center)      # 移動(dòng)窗口矩形到屏幕中心
        self.move(win_rect.center())         # 移動(dòng)窗口與窗口矩形重合
 
    def show_dialog(self):
        dialog = QDialog()
        button = QPushButton("確定", dialog)
        button.clicked.connect(dialog.close)
        button.move(50,50)
        dialog.setWindowTitle("QDialog")
        dialog.setWindowModality(Qt.WindowModality.ApplicationModal)
        dialog.exec()
 
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = MainWindowView()
    view.show()
    sys.exit(app.exec())

結(jié)果:

點(diǎn)擊按鈕可以彈出對(duì)話框,可以添加對(duì)應(yīng)的按鈕關(guān)聯(lián)信號(hào)進(jìn)行窗體關(guān)閉或控制。

使用QMessageBox顯示不同的對(duì)話框

QMessageBox是通用的消息對(duì)話框,包括如下多種形式,不同的對(duì)話框有不同的圖標(biāo)和按鈕,還可以根據(jù)自己需要微調(diào)樣式。

# _*_ coding:utf-8 _*_
 
import sys
 
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QVBoxLayout
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QMessageBox
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
 
 
class DemoQMessageBox(QMainWindow):
    """主窗體界面"""
 
    def __init__(self):
        """構(gòu)造函數(shù)"""
        super().__init__()
 
        self.setWindowTitle("MainWindow")
        self.setWindowIcon(QIcon(r"./res/20 (3).ico"))
        self.resize(300, 200)
        self.setMinimumSize(600, 400)
 
        self.center()
        self.initui()
 
    def initui(self):
        """初始函數(shù)"""
 
        self.vboxlayout = QVBoxLayout(self)
        self.vboxlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.main_widget = QWidget()
        self.main_widget.setLayout(self.vboxlayout)
        self.setCentralWidget(self.main_widget)
 
        btns = ["關(guān)于對(duì)話框", "錯(cuò)誤對(duì)話框", "警告對(duì)話框", "提問(wèn)對(duì)話框", "消息對(duì)話框",]
 
        for btnname in btns:
            """添加button"""
            btn = QPushButton(btnname)
            self.vboxlayout.addWidget(btn)
            btn.clicked.connect(self.show_dialog)
 
    def center(self):
        """居中顯示"""
        win_rect = self.frameGeometry()  # 獲取窗口矩形
        screen_center = self.screen().availableGeometry().center()  # 屏幕中心
        win_rect.moveCenter(screen_center)      # 移動(dòng)窗口矩形到屏幕中心
        self.move(win_rect.center())         # 移動(dòng)窗口與窗口矩形重合
 
    def show_dialog(self):
        if type(self.sender()) is QPushButton:
            btn_text = self.sender().text()
            if btn_text == "關(guān)于對(duì)話框":
                QMessageBox.about(self, "關(guān)于", "這是關(guān)與對(duì)話框")
            elif btn_text == "錯(cuò)誤對(duì)話框":
                QMessageBox.critical(self,"錯(cuò)誤","程序發(fā)生了錯(cuò)誤!",QMessageBox.StandardButton.Ignore | QMessageBox.StandardButton.Abort | QMessageBox.StandardButton.Retry,QMessageBox.StandardButton.Retry)
            elif btn_text == "警告對(duì)話框":
                QMessageBox.warning(
                    self, "警告", "余量不足。", QMessageBox.StandardButton.Ok, QMessageBox.StandardButton.Ok)
            elif btn_text == "提問(wèn)對(duì)話框":
                QMessageBox.question(self, "提問(wèn)", "是否取消" ,QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,QMessageBox.StandardButton.Yes)
            elif btn_text == "消息對(duì)話框":
                QMessageBox.information(
                    self, "消息", "這是通知消息", QMessageBox.StandardButton.Ok, QMessageBox.StandardButton.Ok)
 
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    view = DemoQMessageBox()
    view.show()
    sys.exit(app.exec())

結(jié)果:

點(diǎn)擊不同按鈕,顯示不同的消息窗口:

關(guān)于對(duì)話框:

錯(cuò)誤對(duì)話框:

警告對(duì)話框:

提問(wèn)對(duì)話框:

消息對(duì)話框:

輸入對(duì)話框

輸入對(duì)話框,用于彈窗獲取用戶的輸入信息,包含輸入列表,輸入文本,輸入數(shù)字等方式。

  • QInputDialog.getItem(self,"獲取選項(xiàng)消息框", "名字列表", items),返回值Tuple[str, bool]
  • QInputDialog.getText(self,"獲取文本消息框", "請(qǐng)輸入文本信息:"),返回值Tuple[str, bool]
  • QInputDialog.getInt(self,"獲取整數(shù)消息框", "請(qǐng)輸入整數(shù):"),返回值Tuple[int, bool]
  • QInputDialog.getMultiLineText(parent: QWidget, title: str, label: str, text: str = ..., flags: QtCore.Qt.WindowType = ..., inputMethodHints: QtCore.Qt.InputMethodHint = ...) -> typing.Tuple[str, bool]
  • QInputDialog.getDouble(parent: QWidget, title: str, label: str, value: float = ..., min: float = ..., max: float = ..., decimals: int = ..., flags: QtCore.Qt.WindowType = ..., step: float = ...) -> typing.Tuple[float, bool]

示例:

# _*_ coding:utf-8 _*_
 
import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QFormLayout
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QLineEdit
from PyQt6.QtWidgets import QInputDialog
from PyQt6.QtGui import QColor
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
 
 
class QInputDialogDemoView(QMainWindow):
    """輸入消息框類"""
 
    def __init__(self):
        """構(gòu)造函數(shù)"""
 
        super().__init__()
        self.setWindowTitle("MainWindow")
        self.setWindowIcon(QIcon(r"./res/20 (3).ico"))
        self.resize(200, 100)
        self.center()
        self.initui()
 
    def center(self):
        """居中顯示"""
        win_rect = self.frameGeometry()  # 獲取窗口矩形
        screen_center = self.screen().availableGeometry().center()  # 屏幕中心
        # 移動(dòng)窗口矩形到屏幕中心
        win_rect.moveCenter(screen_center)
        # 移動(dòng)窗口與窗口矩形重合
        self.move(win_rect.center())
 
    def initui(self):
        """初始函數(shù)"""
 
        # 創(chuàng)建表單布局作為底層布局
        self.formlayout = QFormLayout(self)
        self.formlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.main_widget = QWidget()
        self.main_widget.setLayout(self.formlayout)
        self.setCentralWidget(self.main_widget)
 
        # 添加獲取選項(xiàng)按鈕
        self.btn_getitem = QPushButton("Get Item")
        self.btn_getitem.clicked.connect(self.get_item)
        self.ledit_getitem = QLineEdit()
        self.formlayout.addRow(self.btn_getitem, self.ledit_getitem)
 
        # 添加獲取文本按鈕
        self.btn_gettext = QPushButton("Get Text")
        self.btn_gettext.clicked.connect(self.get_text)
        self.ledit_gettext = QLineEdit()
        self.formlayout.addRow(self.btn_gettext, self.ledit_gettext)
 
        # 添加獲取整數(shù)按鈕
        self.btn_getint = QPushButton("Get Int")
        self.btn_getint.clicked.connect(self.get_int)
        self.ledit_getint = QLineEdit()
        self.formlayout.addRow(self.btn_getint, self.ledit_getint)
 
    def get_item(self):
        """獲取選項(xiàng)槽"""
        items = ("小張", "小明", "小李", "小朱")
        item,result = QInputDialog.getItem(self,"獲取選項(xiàng)消息框", "名字列表", items)
        print(f"item : {item}, ok : {result}, tpye : {type(result)}")
        if item and result:
            self.ledit_getitem.setText(item)
 
    def get_text(self):
        """獲取文本槽"""
        text,result = QInputDialog.getText(self,"獲取文本消息框", "請(qǐng)輸入文本信息:")
        print(f"item : {text}, ok : {result}, tpye : {type(result)}")
        if text and result:
            self.ledit_gettext.setText(text)
 
 
    def get_int(self):
        """獲取文本槽"""
        num,result = QInputDialog.getInt(self,"獲取整數(shù)消息框", "請(qǐng)輸入整數(shù):")
        print(f"item : {num}, ok : {result}, tpye : {type(result)}")
        if num and result:
            self.ledit_getint.setText(str(num))
 
 
 
if __name__ == "__main__":
    """主程序運(yùn)行"""
    app = QApplication(sys.argv)
    window = QInputDialogDemoView()
    window.show()
    sys.exit(app.exec())

結(jié)果:

主界面:

輸入選項(xiàng):

輸入文本:

輸入整數(shù):

字體對(duì)話框

字體對(duì)話框(QFontDialog)可以用來(lái)交互選擇系統(tǒng)中的字體然后通過(guò)返回的QFont類型數(shù)據(jù)來(lái)設(shè)置相關(guān)的字體。

font, ok = QFontDialog.getFont()

示例:

# _*_ coding:utf-8 _*_
 
import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QFontDialog
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QLabel
from PyQt6.QtWidgets import QVBoxLayout
from PyQt6.QtGui import QFont
from PyQt6.QtCore import Qt 
 
 
class QFontDialogDemo(QMainWindow):
    """字體對(duì)話框"""
 
    def __init__(self):
        """構(gòu)造函數(shù)"""
 
        super(QFontDialogDemo,self).__init__()
        self.init_ui()
 
    def init_ui(self):
        self.setWindowTitle("QFontDialogDemo")
        self.resize(300, 200)
 
        # 獲取中央控件
        self.centralwidget = QWidget()
        self.setCentralWidget(self.centralwidget)
 
        # 設(shè)置布局
        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.centralwidget.setLayout(self.vboxlayout)
 
        # 添加標(biāo)簽和按鈕
        self.label = QLabel("字體樣式展示")
        self.vboxlayout.addWidget(self.label)
        self.label_fonttype = QLabel("字體類型")
        self.vboxlayout.addWidget(self.label_fonttype)
        self.btn_showfontdialog = QPushButton("選擇字體")
        self.btn_showfontdialog.clicked.connect(self.getfont)
        self.vboxlayout.addWidget(self.btn_showfontdialog)
        
 
    def getfont(self):
        """獲取字體"""
        font, ok = QFontDialog.getFont()
        if ok :
            self.label.setFont(font)
            self.label_fonttype.setText(f"字體名稱:{font.family()},樣式:{font.styleName()},字號(hào):{font.pointSize()}")
 
 
if __name__ == "__main__":
    """主程序運(yùn)行"""
    
    app = QApplication(sys.argv)
    main = QFontDialogDemo()
    main.show()
    sys.exit(app.exec())

結(jié)果:

界面樣式:

字體彈窗:

設(shè)置字體后:

顏色對(duì)話框

通過(guò)顏色對(duì)話框(QColorDialog)選擇顏色,然后給給控件設(shè)置對(duì)應(yīng)的顏色。

格式:

color, ok = QColorDialog.getColor()

示例:

# _*_ coding:utf-8 _*_
 
import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QColorDialog
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QLabel
from PyQt6.QtWidgets import QVBoxLayout
from PyQt6.QtGui import QPalette
from PyQt6.QtCore import Qt
 
 
class QColorDialogDemo(QMainWindow):
    """字體對(duì)話框"""
 
    def __init__(self):
        """構(gòu)造函數(shù)"""
 
        super(QColorDialogDemo, self).__init__()
        self.init_ui()
 
    def init_ui(self):
        self.setWindowTitle("QColorDialogDemo")
        self.resize(300, 200)
 
        # 獲取中央控件
        self.centralwidget = QWidget()
        self.setCentralWidget(self.centralwidget)
 
        # 設(shè)置布局
        self.vboxlayout = QVBoxLayout()
        self.vboxlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.centralwidget.setLayout(self.vboxlayout)
 
        # 添加標(biāo)簽和按鈕
        self.label = QLabel("字體顏色展示")
        self.vboxlayout.addWidget(self.label)
        self.label_fonttype = QLabel("顏色:")
        self.vboxlayout.addWidget(self.label_fonttype)
        self.btn_showcolordialog = QPushButton("選擇字體顏色")
        self.btn_showcolordialog.clicked.connect(self.getcolor)
        self.vboxlayout.addWidget(self.btn_showcolordialog)
        self.btn_showcolordialog_background = QPushButton("選擇背景顏色")
        self.btn_showcolordialog_background.clicked.connect(
            self.getcolor_background)
        self.vboxlayout.addWidget(self.btn_showcolordialog_background)
 
    def getcolor(self):
        """獲取顏色"""
        color = QColorDialog.getColor()
        
        palette = QPalette()
        palette.setColor(QPalette.ColorRole.WindowText, color)
        self.label.setPalette(palette)
        self.label_fonttype.setText("""顏色:{0:x}""".format(color.rgb()))
 
    def getcolor_background(self):
        """獲取背景顏色"""
        color = QColorDialog.getColor()
 
        palette = QPalette()
        palette.setColor(QPalette.ColorRole.Window, color)
        self.label.setAutoFillBackground(True)
        self.label.setPalette(palette)
        self.label_fonttype.setText("""顏色:{0:x}""".format(color.rgb()))
 
if __name__ == "__main__":
    """主程序運(yùn)行"""
 
    app = QApplication(sys.argv)
    main = QColorDialogDemo()
    main.show()
    sys.exit(app.exec())

結(jié)果:

界面:

調(diào)色板:

修改顏色字體:

修改背景顏色:

文件對(duì)話框

文件對(duì)話框(QFileDialog)用于瀏覽文件并獲取文件路徑。

使用靜態(tài)方法獲取文件路徑

  • getSaveFileName(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., filter: str = ..., initialFilter: str = ..., options: 'QFileDialog.Option' = ...) -> typing.Tuple[str, str]: ...
  • getOpenFileNames(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., filter: str = ..., initialFilter: str = ..., options: 'QFileDialog.Option' = ...) -> typing.Tuple[typing.List[str], str]: ...
  • getOpenFileName(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., filter: str = ..., initialFilter: str = ..., options: 'QFileDialog.Option' = ...) -> typing.Tuple[str, str]: ...
  • getExistingDirectoryUrl(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: QtCore.QUrl = ..., options: 'QFileDialog.Option' = ..., supportedSchemes: typing.Iterable[str] = ...) -> QtCore.QUrl: ...
  • getExistingDirectory(parent: typing.Optional[QWidget] = ..., caption: str = ..., directory: str = ..., options: 'QFileDialog.Option' = ...) -> str: ...

示例:

# _*_ coding:utf-8 _*_
 
import sys
from PyQt6.QtWidgets import QApplication
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QMainWindow
from PyQt6.QtWidgets import QFileDialog
from PyQt6.QtWidgets import QPushButton
from PyQt6.QtWidgets import QLabel
from PyQt6.QtWidgets import QLineEdit
from PyQt6.QtWidgets import QFormLayout
from PyQt6.QtGui import QPalette
from PyQt6.QtCore import Qt
 
 
class QFileDialogDemo(QMainWindow):
    """字體對(duì)話框"""
 
    def __init__(self):
        """構(gòu)造函數(shù)"""
 
        super(QFileDialogDemo, self).__init__()
        self.init_ui()
 
    def init_ui(self):
        self.setWindowTitle("QColorDialogDemo")
        self.resize(400, 200)
 
        # 獲取中央控件
        self.centralwidget = QWidget()
        self.setCentralWidget(self.centralwidget)
 
        # 設(shè)置布局
        self.formlayout = QFormLayout()
        self.formlayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.centralwidget.setLayout(self.formlayout)
 
        # 添加標(biāo)簽和按鈕
        self.label = QLabel("文件路徑:")
        self.ledit_filepath = QLineEdit()
        self.formlayout.addRow(self.label, self.ledit_filepath)
 
        self.btn_openfile = QPushButton("打開(kāi)文件")
        self.btn_openfile.clicked.connect(self.openfile)
        self.formlayout.addWidget(self.btn_openfile)
 
    def openfile(self):
        """獲取顏色"""
        # filename->返回的文件路徑,filetypelist->設(shè)置的要打開(kāi)的文件類型
        filename, filetypelist = QFileDialog.getOpenFileName(
            self, "Open File", r"D:\Desktop", "文本文件(*.txt *.csv)")
        self.ledit_filepath.setText(filename + ";" + filetypelist)
 
if __name__ == "__main__":
    """主程序運(yùn)行"""
 
    app = QApplication(sys.argv)
    main = QFileDialogDemo()
    main.show()
    sys.exit(app.exec())

結(jié)果:

實(shí)例化對(duì)話框獲取文件路徑

實(shí)際使用過(guò)程中也可以通過(guò)自己需求實(shí)例化文件對(duì)話框后,配置文件對(duì)話框?qū)傩裕缓笤佾@取文件路徑。

        filedialog = QFileDialog()
        filedialog.setFileMode(QFileDialog.FileMode.AnyFile)
        filedialog.setFilter(QDir.Filter.Files)
 
        if filedialog.exec():
            filenames = filedialog.selectedFiles()
            self.ledit_filepath.setText(filenames[0])

到此這篇關(guān)于Python之PyQt6對(duì)話框的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python之PyQt6對(duì)話框內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論