pyqt5 qmessagebox
时间: 2023-09-05 15:14:19 浏览: 95
PyQt5基本控件之QMessageBox
QMessageBox is a class in PyQt5 that provides a simple way to display message boxes. These message boxes can be used to display information to the user or to get input from the user.
To use QMessageBox in PyQt5, you first need to import it:
```python
from PyQt5.QtWidgets import QMessageBox
```
Once you have imported QMessageBox, you can create an instance of it and set its properties. Here's an example:
```python
msg_box = QMessageBox()
msg_box.setText("Hello, world!")
msg_box.setWindowTitle("My Message Box")
msg_box.setIcon(QMessageBox.Information)
msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msg_box.setDefaultButton(QMessageBox.Ok)
```
In this example, we create a message box with the text "Hello, world!", a title of "My Message Box", an information icon, and two standard buttons (Ok and Cancel). We also set the default button to be the Ok button.
To display the message box, you can call its exec() method:
```python
result = msg_box.exec_()
```
This will display the message box and wait for the user to interact with it. When the user clicks a button, the exec() method will return a value indicating which button was clicked. In this example, we store the result in the variable result.
Here's an example that shows how to use QMessageBox to get input from the user:
```python
name, ok_pressed = QMessageBox.getText(
None, "Get Name", "Enter your name:")
if ok_pressed:
print("Hello, " + name)
```
In this example, we use the static method getText() to display a message box with a text input field. We pass in the parent widget (None), a title of "Get Name", and a message of "Enter your name:". The method returns two values: the text entered by the user and a boolean indicating whether the Ok button was pressed. If the Ok button was pressed, we print a greeting to the console.
阅读全文