PyQt6入门之QMessageBox部件

当用户关闭一个应用程序或保存他们的工作,或发生错误时,他们通常会看到一个对话框弹出并显示某种关键信息。然后,用户可以与该对话框互动,通常是通过点击一个按钮来回应提示。 对话框是一种非常重要的反馈形式,或者说是监测和向用户反馈变化的方法。

QMessageBox类不仅可以用来提醒用户注意某种情况,还可以用来决定如何处理这件事。例如,当关闭一个你刚刚修改过的文档时,你可能会得到一个对话框,其中的按钮要求你保存、不保存或取消。

窗口 Vs. 对话框

应用程序通常由一个主窗口组成。窗口用于在视觉上将应用程序彼此分开,通常由菜单、工具栏和其他种类的部件组成,它们通常可以作为GUI应用程序的主要界面。

Qt中的窗口通常被认为是出现在屏幕上的部件,没有一个父部件。 对话框,或简称对话框,当用户在主窗口工作时,会弹出并显示选项或信息。大多数种类的对话框都会有一个父窗口,用来确定对话框相对于其所有者的位置。这也意味着,窗口和对话框之间会发生通信,对话框可以用来更新主窗口。

有两种类型的对话框。模态对话框阻止用户与程序其他部分的交互,直到对话框被关闭。无模式对话框允许用户与对话框和程序的其他部分进行交互。

接下来完成整个GUI设计流程

  • 创建空白的GUI主窗口界面
# message_boxes.py
# Import necessary modules
import sys
from PyQt6.QtWidgets import (QApplication, QWidget, QLabel, QMessageBox, QLineEdit, QPushButton)
from PyQt6.QtGui import QFont


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initializeUI()

    
    def initializeUI(self):
        """Set up the application's GUI."""
        self.setGeometry(100, 100, 340, 140)
        self.setWindowTitle("QMessage Example")

        # self.setUpMainWindow()
        self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

Alt

  • 创建主窗口内容部件

创建QLabel对象,QLineEdit组件用于用户输入作者名字,以及一个QPushButton对象用于当发送信号和在text文件中寻找文本。

catalogue_label和search_label这些部件是用来向用户传达信息的。在PyQt中,QLabel部件经常被放在QLineEdit和其他输入部件旁边作为标签。然后,这些标签可以作为伙伴链接到输入部件上。在这里,author_label和author_edit被简单地放在彼此的旁边。

占位符文本可以用来给用户提供关于QLineEdit小组件的目的的额外信息,或者用于如何格式化输入文本。这可以通过setPlaceholderText()来实现。

当用户点击搜索按钮时,程序将尝试打开author.txt文件并将其内容存储在作者列表中。如果用户在author_edit中输入的名字包含在author.txt文件中,会出现一个信息对话框提示找到相应的作者名。

要从一个预定义的类型中创建一个QMessageBox对话框,首先,创建一个QMessageBox对象并调用其中一个静态函数,在本例中是信息。接下来,传递父部件。然后设置对话框的标题,“找到作者”,以及将出现在对话框内提供反馈的文本,可能还有关于用户可以采取的行动的信息。接下来是将出现在对话框中的标准按钮的类型。可以使用多个按钮,并用管状键分隔,|。标准按钮包括打开、保存、取消、重置、是和否。

如果没有找到作者,就会出现一个问题对话框,询问用户是否要再次搜索或退出程序。标准按钮Yes和No出现在窗口中。最后一个参数用于指定你想在对话框中突出哪个按钮,并设置为默认按钮。

注意 PyQt文本部件能够使用超文本标记语言(HTML)和层叠样式表(CSS)的一个子集来显示丰富的文本。这个话题在后面章节会有更多的探讨,但现在,我们将使用HTML把放在HTML标签 <p> 和 </p> 之间的文本安排成段落。

Alt
Alt
Alt

完整程序示例如下

# message_boxes.py
# Import necessary modules
import sys
from PyQt6.QtWidgets import (QApplication, QWidget, QLabel, QMessageBox, QLineEdit, QPushButton)
from PyQt6.QtGui import QFont


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initializeUI()

    
    def initializeUI(self):
        """Set up the application's GUI."""
        self.setGeometry(100, 100, 340, 140)
        self.setWindowTitle("QMessage Example")

        self.setUpMainWindow()
        self.show()


    def setUpMainWindow(self):
        """Create and arrange widgets in the main window."""
        catalogue_label = QLabel("Author Catalogue", self)
        catalogue_label.move(100, 10)
        catalogue_label.setFont(QFont("Arial", 18))

        search_label = QLabel("Search the index for an author:", self)
        search_label.move(20, 40)

        # Create author QLabel and QLineEdit widgets
        author_label = QLabel("Name:", self)
        author_label.move(20, 74)

        self.author_edit = QLineEdit(self)
        self.author_edit.move(70, 70)
        self.author_edit.resize(240, 24)
        self.author_edit.setPlaceholderText("Enter names as: First Last")

        # Create the search QPushButton
        search_button = QPushButton("Search", self)
        search_button.move(140, 100)
        search_button.clicked.connect(self.searchAuthors)


    def searchAuthors(self):
        """
            Search through a catalogue of names.
        If a name is found, display the Author Found dialog.
        Otherwise, display the Author Not Found dialog.
        """
        file = "files/authors.txt"

        try:
            with open (file, "r") as f:
                authors = [line.rstrip("\n") for line in f]
            
            # Check for name in authors list
            if self.author_edit.text() in authors:
                QMessageBox.information(self, "Author Found",
                                        "Author found in the catalogue!",
                                        QMessageBox.StandardButton.Ok)
            else:
                answer = QMessageBox.question(self, "Author Not Found",
                                              """<p>Author not found in catalogue.</p>
                                                 <p>Do you wish to continue?</p>""",
                                                QMessageBox.StandardButton.Yes | \
                                                QMessageBox.StandardButton.No,
                                                QMessageBox.StandardButton.No)
                if answer == QMessageBox.StandardButton.No:
                    print("Closing application.")
                    self.close()
                    
                
        except FileNotFoundError as error:
            QMessageBox.warning(self, "Error",
                                f"""<p>File not found.</p>
                                    <p>Error: {error}</p>
                                    Closing application.""",
                                QMessageBox.StandardButton.Ok)
            self.close()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

文中主要简要介绍部件的基本运用方法,程序中存在许多不足之处,读者可在此基础上进行修改和完善,并按照自己的需求进行调整。同时,文中不足之处也望读者多多海涵。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值