Pyqt error message

QErrorMessageВ¶ The QErrorMessage class provides an error message display dialog. More… SynopsisВ¶ SlotsВ¶ Static functionsВ¶ Detailed DescriptionВ¶ An error message widget consists of a text label and a checkbox. The checkbox lets the user control whether the same error message will be displayed again in the future, typically displaying the text, “Show this message […]

Public Slots

void showMessage(const QString &message, const QString &type)
void showMessage(const QString &message)

Static Public Members

Reimplemented Protected Functions

virtual void changeEvent(QEvent *e) override
virtual void done(int a) override

Detailed Description

An error message widget consists of a text label and a checkbox. The checkbox lets the user control whether the same error message will be displayed again in the future, typically displaying the text, «Show this message again» translated into the appropriate local language.

For production applications, the class can be used to display messages which the user only needs to see once. To use QErrorMessage like this, you create the dialog in the usual way, and show it by calling the showMessage() slot or connecting signals to it.

The static qtHandler() function installs a message handler using qInstallMessageHandler() and creates a QErrorMessage that displays qDebug(), qWarning() and qFatal() messages. This is most useful in environments where no console is available to display warnings and error messages.

In both cases QErrorMessage will queue pending messages and display them in order, with each new message being shown as soon as the user has accepted the previous message. Once the user has specified that a message is not to be shown again it is automatically skipped, and the dialog will show the next appropriate message in the queue.

The Standard Dialogs example shows how to use QErrorMessage as well as other built-in Qt dialogs.

Member Function Documentation

QErrorMessage:: QErrorMessage ( QWidget *parent = nullptr)

Constructs and installs an error handler window with the given parent.

[slot] void QErrorMessage:: showMessage (const QString &message, const QString &type)

This is an overloaded function.

Shows the given message, message, and returns immediately. If the user has requested for messages of type, type, not to be shown again, this function does nothing.

Normally, the message is displayed immediately. However, if there are pending messages, it will be queued to be displayed later.

[slot] void QErrorMessage:: showMessage (const QString &message)

Shows the given message, message, and returns immediately. If the user has requested for the message not to be shown again, this function does nothing.

Normally, the message is displayed immediately. However, if there are pending messages, it will be queued to be displayed later.

[virtual] QErrorMessage::

Destroys the error message dialog.

[override virtual protected] void QErrorMessage:: changeEvent ( QEvent *e)

[override virtual protected] void QErrorMessage:: done ( int a)

[static] QErrorMessage *QErrorMessage:: qtHandler ()

Returns a pointer to a QErrorMessage object that outputs the default Qt messages. This function creates such an object, if there isn’t one already.

В© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

PyQt5 Dialogs and Alerts
Notify your users and ask for their input

PyQt5 Tutorial — Getting started with PyQt5

This tutorial is also available for PyQt6 , PySide6 and PySide2

Dialogs are useful GUI components that allow you to communicate with the user (hence the name dialog). They are commonly used for file Open/Save, settings, preferences, or for functions that do not fit into the main UI of the application. They are small modal (or blocking) windows that sit in front of the main application until they are dismissed. Qt provides a number of ‘special’ built-in dialogs for the most common use-cases, allowing you to provide a platform-native user experience.

Standard GUI features — A search dialog

Standard GUI features — A file Open dialog

In Qt dialog boxes are handled by the QDialog class. To create a new dialog box simply create a new object of QDialog type passing in another widget, e.g. QMainWindow , as its parent.

Let’s create our own QDialog . We’ll start with a simple skeleton app with a button to press hooked up to a slot method.

In the slot button_clicked (which receives the signal from the button press) we create the dialog instance, passing our QMainWindow instance as a parent. This will make the dialog a modal window of QMainWindow . This means the dialog will completely block interaction with the parent window.

Run it! Click the button and you’ll see an empty dialog appear.

Once we have created the dialog, we start it using .exec() — just like we did for QApplication to create the main event loop of our application. That’s not a coincidence: when you exec the QDialog an entirely new event loop — specific for the dialog — is created.

The QDialog completely blocks your application execution. Don’t start a dialog and expect anything else to happen anywhere else in your app. We’ll see later how you can use threads & processes to get you out of this pickle.

Our empty dialog overlaying the window.

Like our very first window, this isn’t very interesting. Let’s fix that by adding a dialog title and a set of OK and Cancel buttons to allow the user to accept or reject the modal.

To customize the QDialog we can subclass it.

In the above code, we first create our subclass of QDialog which we’ve called CustomDialog . As for the QMainWindow we apply our customizations in the class __init__ block so our customizations are applied as the object is created. First we set a title for the QDialog using .setWindowTitle() , exactly the same as we did for our main window.

The next block of code is concerned with creating and displaying the dialog buttons. This is probably a bit more involved than you were expecting. However, this is due to Qt’s flexibility in handling dialog button positioning on different platforms.

You could of course choose to ignore this and use a standard QButton in a layout, but the approach outlined here ensures that your dialog respects the host desktop standards (OK on left vs. right for example). Messing around with these behaviors can be incredibly annoying to your users, so I wouldn’t recommend it.

The first step in creating a dialog button box is to define the buttons want to show, using namespace attributes from QDialogButtonBox . The full list of buttons available is below.

  • QDialogButtonBox.Ok
  • QDialogButtonBox.Open
  • QDialogButtonBox.Save
  • QDialogButtonBox.Cancel
  • QDialogButtonBox.Close
  • QDialogButtonBox.Discard
  • QDialogButtonBox.Apply
  • QDialogButtonBox.Reset
  • QDialogButtonBox.RestoreDefaults
  • QDialogButtonBox.Help
  • QDialogButtonBox.SaveAll
  • QDialogButtonBox.Yes
  • QDialogButtonBox.YesToAll
  • QDialogButtonBox.No
  • QDialogButtonBox.Abort
  • QDialogButtonBox.Retry
  • QDialogButtonBox.Ignore
  • QDialogButtonBox.NoButton

These should be sufficient to create any dialog box you can think of. You can construct a line of multiple buttons by OR-ing them together using a pipe ( | ). Qt will handle the order automatically, according to platform standards. For example, to show an OK and a Cancel button we used:

The variable buttons now contains an integer value representing those two buttons. Next, we must create the QDialogButtonBox instance to hold the buttons. The flag for the buttons to display is passed in as the first parameter.

To make the buttons have any effect, you must connect the correct QDialogButtonBox signals to the slots on the dialog. In our case we’ve connected the .accepted and .rejected signals from the QDialogButtonBox to the handlers for .accept() and .reject() on our subclass of QDialog .

Lastly, to make the QDialogButtonBox appear in our dialog box we must add it to the dialog layout. So, as for the main window we create a layout, and add our QDialogButtonBox to it ( QDialogButtonBox is a widget), and then set that layout on our dialog.

Finally, we launch the CustomDialog in our MainWindow.button_clicked slot.

Run it! Click to launch the dialog and you will see a dialog box with buttons.

Our dialog with a label and buttons.

When you click the button to launch the dialog, you may notice that it appears away from the parent window — probably in the center of the screen. Normally you want dialogs to appear over their launching window to make them easier for users to find. To do this we need to give Qt a parent for the dialog. If we pass our main window as the parent, Qt will position the new dialog so that the center of the dialog aligns with the center of the window.

We can modify our CustomDialog class to accept a parent parameter.

We set a default value of parent=None so we can omit the parent if we wish.

Then, when we create our instance of CustomDialog we can pass the main window in as a parameter. In our button_clicked method, self is our main window object.

Run it! Click to launch the dialog and you should see the dialog pop up right in the middle of the parent window.

Our dialog, centered over the parent window.

Congratulations! You’ve created your first dialog box. Of course, you can continue to add any other content to the dialog box that you like. Simply insert it into the layout as normal.

Simple message dialogs with QMessageBox

There are many dialogs which follow the simple pattern we just saw — a message with buttons with which you can accept or cancel the dialog. While you can construct these dialogs yourself, Qt also provides a built-in message dialog class called QMessageBox . This can be used to create information, warning, about or question dialogs.

The example below creates a simple QMessageBox and shows it.

Run it! You’ll see a simple dialog with an OK button.

A QMessageBox dialog.

As with the dialog button box we looked at already, the buttons shown on a QMessageBox are also configured with the same set of constants which can be combined with | (the binary OR operator) to show multiple buttons. The full list of available button types is shown below.

  • QMessageBox.Ok
  • QMessageBox.Open
  • QMessageBox.Save
  • QMessageBox.Cancel
  • QMessageBox.Close
  • QMessageBox.Discard
  • QMessageBox.Apply
  • QMessageBox.Reset
  • QMessageBox.RestoreDefaults
  • QMessageBox.Help
  • QMessageBox.SaveAll
  • QMessageBox.Yes
  • QMessageBox.YesToAll
  • QMessageBox.No
  • QMessageBox.NoToAll
  • QMessageBox.Abort
  • QMessageBox.Retry
  • QMessageBox.Ignore
  • QMessageBox.NoButton

You can also tweak the icon shown on the dialog by setting the icon with one of the following.

Icon state Description
QMessageBox.NoIcon The message box does not have an icon.
QMessageBox.Question The message is asking a question.
QMessageBox.Information The message is informational only.
QMessageBox.Warning The message is warning.
QMessageBox.Critical The message indicates a critical problem.

For example, the following creates a question dialog with Yes and No buttons.

Run it! You’ll see a question dialog with Yes and No buttons.

Question dialog created using QMessageBox.

Источник

Adblock
detector

QErrorMessage Class Reference
[QtGui module]

The QErrorMessage class provides an error message display
dialog. More…

Inherits QDialog.

Methods

  • __init__ (self, QWidget parent = None)

  • showMessage (self, QString message, QString type)

Static Methods


Detailed Description

The QErrorMessage class provides an error message display
dialog.

An error message widget consists of a text label and a checkbox.
The checkbox lets the user control whether the same error message
will be displayed again in the future, typically displaying the
text, «Show this message again» translated into the appropriate
local language.

For production applications, the class can be used to display
messages which the user only needs to see once. To use
QErrorMessage like this, you create the dialog in the usual way,
and show it by calling the showMessage() slot or
connecting signals to it.

The static qtHandler() function installs a
message handler using qInstallMsgHandler() and
creates a QErrorMessage that displays qDebug(), qWarning() and qFatal() messages. This is most useful
in environments where no console is available to display warnings
and error messages.

In both cases QErrorMessage will queue pending messages and
display them in order, with each new message being shown as soon as
the user has accepted the previous message. Once the user has
specified that a message is not to be shown again it is
automatically skipped, and the dialog will show the next
appropriate message in the queue.

The Standard Dialogs
example shows how to use QErrorMessage as well as other built-in Qt
dialogs.


Method Documentation

QErrorMessage.__init__ (self, QWidget parent = None)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs and installs an error handler window with the given
parent.

QErrorMessage.changeEvent (self, QEvent e)

Reimplemented from QWidget.changeEvent().

QErrorMessage.done (self, int)

Reimplemented from QDialog.done().

QErrorMessage QErrorMessage.qtHandler ()

Returns a pointer to a QErrorMessage object that outputs the
default Qt messages. This function creates such an object, if there
isn’t one already.

QErrorMessage.showMessage (self, QString message)

This method is also a Qt slot with the C++ signature void showMessage(const QString&).

Shows the given message, message, and returns
immediately. If the user has requested for the message not to be
shown again, this function does nothing.

Normally, the message is displayed immediately. However, if
there are pending messages, it will be queued to be displayed
later.

QErrorMessage.showMessage (self, QString message, QString type)

This method is also a Qt slot with the C++ signature void showMessage(const QString&,const QString&).

This is an overloaded function.

Shows the given message, message, and returns
immediately. If the user has requested for messages of type,
type, not to be shown again, this function does nothing.

Normally, the message is displayed immediately. However, if
there are pending messages, it will be queued to be displayed
later.

This function was introduced in Qt 4.5.

See also showMessage().


In this article, we will discuss the Message Box Widget of the PyQT5 module. It is used to display the message boxes. PyQt5 is a library used to create GUI using the Qt GUI framework. Qt is originally written in C++ but can be used in Python. The latest version of PyQt5 can be installed using the command:

pip install PyQt5

What is a Message Box?

Message Boxes are usually used for declaring a small piece of information to the user. It gives users a pop-up box, that cannot be missed, to avoid important errors and information being missed by the users and in some cases, the user cannot continue without acknowledging the message box.

Based on the applications there are four types of message boxes. The following is the syntax for creating a message box. For any of the boxes, instantiation needs to be done.

Syntax:

msg_box_name = QMessageBox() 

Now according to the requirement an appropriate message box is created.

Types of Message Box

Information Message Box

This type of message box is used when related information needs to be passed to the user.

Syntax:

msg_box_name.setIcon(QMessageBox.Information) 

Question Message Box

This message box is used to get an answer from a user regarding some activity or action to be performed.

Syntax:

msg_box_name.setIcon(QMessageBox.Question)

Warning Message Box

This triggers a warning regarding the action the user is about to perform.

Syntax:

msg_box_name.setIcon(QMessageBox.Warning)

Critical Message Box

This is often used for getting the user’s opinion for a critical action.  

Syntax:

msg_box_name.setIcon(QMessageBox.Critical)

Creating a simple Message Box using PyQt5

Now to create a program that produces a message box first import all the required modules, and create a widget with four buttons, on clicking any of these a message box will be generated.  

Now for each button associate a message box that pops when the respective button is clicked. For this first, instantiate a message box and add a required icon. Now set appropriate attributes for the pop that will be generated. Also, add buttons to deal with standard mechanisms.

Given below is the complete implementation.

Program:

Python

import sys

from PyQt5.QtWidgets import *

def window():

    app = QApplication(sys.argv)

    w = QWidget()

    b1 = QPushButton(w)

    b1.setText("Information")

    b1.move(45, 50)

    b2 = QPushButton(w)

    b2.setText("Warning")

    b2.move(150, 50)

    b3 = QPushButton(w)

    b3.setText("Question")

    b3.move(50, 150)

    b4 = QPushButton(w)

    b4.setText("Critical")

    b4.move(150, 150)

    b1.clicked.connect(show_info_messagebox)

    b2.clicked.connect(show_warning_messagebox)

    b3.clicked.connect(show_question_messagebox)

    b4.clicked.connect(show_critical_messagebox)

    w.setWindowTitle("PyQt MessageBox")

    w.show()

    sys.exit(app.exec_())

def show_info_messagebox():

    msg = QMessageBox()

    msg.setIcon(QMessageBox.Information)

    msg.setText("Information ")

    msg.setWindowTitle("Information MessageBox")

    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

    retval = msg.exec_()

def show_warning_messagebox():

    msg = QMessageBox()

    msg.setIcon(QMessageBox.Warning)

    msg.setText("Warning")

    msg.setWindowTitle("Warning MessageBox")

    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

    retval = msg.exec_()

def show_question_messagebox():

    msg = QMessageBox()

    msg.setIcon(QMessageBox.Question)

    msg.setText("Question")

    msg.setWindowTitle("Question MessageBox")

    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

    retval = msg.exec_()

def show_critical_messagebox():

    msg = QMessageBox()

    msg.setIcon(QMessageBox.Critical)

    msg.setText("Critical")

    msg.setWindowTitle("Critical MessageBox")

    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

    retval = msg.exec_()

if __name__ == '__main__':

    window()

Output

Here are the examples of the python api PyQt5.QtWidgets.QErrorMessage taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.


5

Example 1

    def handle_error(self, error):
        """Handle when an error occurs

        Show the error in an error message window.
        """
        em = QErrorMessage(self.main_window)
        em.showMessage(error)


3

Example 2

    def first_channel_changed(self, index):
        self.parent().ui.actionStart.setChecked(False)

        success, index = self.audiobackend.select_first_channel(index)

        self.comboBox_firstChannel.setCurrentIndex(index)

        if not success:
            # Note: the error message is a child of the settings dialog, so that
            # that dialog remains on top when the error message is closed
            error_message = QtWidgets.QErrorMessage(self)
            error_message.setWindowTitle("Input device error")
            error_message.showMessage("Impossible to use the selected channel as the first channel, reverting to the previous one")

        self.parent().ui.actionStart.setChecked(True)


3

Example 3

    def second_channel_changed(self, index):
        self.parent().ui.actionStart.setChecked(False)

        success, index = self.audiobackend.select_second_channel(index)

        self.comboBox_secondChannel.setCurrentIndex(index)

        if not success:
            # Note: the error message is a child of the settings dialog, so that
            # that dialog remains on top when the error message is closed
            error_message = QtWidgets.QErrorMessage(self)
            error_message.setWindowTitle("Input device error")
            error_message.showMessage("Impossible to use the selected channel as the second channel, reverting to the previous one")

        self.parent().ui.actionStart.setChecked(True)


0

Example 4

    def device_changed(self, index):
        device = self.audiobackend.output_devices[index]

        # save current stream in case we need to restore it
        previous_stream = self.stream
        previous_device = self.device

        error_message = ""

        self.logger.push("Trying to write to output device " + device['name'])

        # first see if the format is supported by PortAudio
        try:
            success = self.audiobackend.is_output_format_supported(device, np.int16)
        except Exception as exception:
            self.logger.push("Format is not supported: " + str(exception))
            success = False

        if success:
            try:
                self.stream = self.audiobackend.open_output_stream(device, self.audio_callback)
                self.device = device
                self.stream.start()
                if self.state not in [STARTING, PLAYING]:
                    self.stream.stop()
                success = True
            except OSError as error:
                self.logger.push("Fail: " + str(error))
                success = False

        if success:
            self.logger.push("Success")
            previous_stream.stop()
        else:
            if self.stream is not None:
                self.stream.stop()
            # restore previous stream
            self.stream = previous_stream
            self.device = previous_device

            # Note: the error message is a child of the settings dialog, so that
            # that dialog remains on top when the error message is closed
            error_message = QtWidgets.QErrorMessage(self.settings_dialog)
            error_message.setWindowTitle("Output device error")
            error_message.showMessage("Impossible to use the selected output device, reverting to the previous one. Reason is: " + error_message)

        self.settings_dialog.combobox_output_device.setCurrentIndex(self.audiobackend.output_devices.index(self.device))


0

Example 5

    def input_device_changed(self, index):
        self.parent().ui.actionStart.setChecked(False)

        success, index = self.audiobackend.select_input_device(index)

        self.comboBox_inputDevice.setCurrentIndex(index)

        if not success:
            # Note: the error message is a child of the settings dialog, so that
            # that dialog remains on top when the error message is closed
            error_message = QtWidgets.QErrorMessage(self)
            error_message.setWindowTitle("Input device error")
            error_message.showMessage("Impossible to use the selected input device, reverting to the previous one")

        # reset the channels
        channels = self.audiobackend.get_readable_current_channels()

        self.comboBox_firstChannel.clear()
        self.comboBox_secondChannel.clear()

        for channel in channels:
            self.comboBox_firstChannel.addItem(channel)
            self.comboBox_secondChannel.addItem(channel)

        first_channel = self.audiobackend.get_current_first_channel()
        self.comboBox_firstChannel.setCurrentIndex(first_channel)
        second_channel = self.audiobackend.get_current_second_channel()
        self.comboBox_secondChannel.setCurrentIndex(second_channel)

        self.parent().ui.actionStart.setChecked(True)

Понравилась статья? Поделить с друзьями:
  • Px4 ahrs error
  • Pwm9141 05 ошибка вольво
  • Pwg error incomplete session by timeout
  • Pylint ignore error
  • Pvz heroes ошибка подключения к сети как исправить