PyQt QMessageBox、を使用してダイアログを作成できます。 これは、デスクトップでよく見かける小さなポップアップウィンドウです。
「保存してもよろしいですか?」という1行のメッセージの場合があります。 メッセージまたはより高度なもの。
このメッセージボックスは、あらゆる種類のバリエーションとボタンをサポートしています。 このレッスンでは、情報ダイアログウィンドウを作成する方法を学習します。
関連コース: PythonPyQt5でGUIアプリを作成する
ダイアログ
初期ウィンドウ
ボタン付きのウィンドウを作成します。 ボタンをクリックすると、ダイアログがポップアップ表示されます。
(これは、PyQtが初期化される場所でもあります。)
1 2 3 4 5 6 7 8 9 10 11
|
def window(): app = QApplication(sys.argv) win = QWidget() button1 = QPushButton(win) button1.setText("Show dialog!") button1.move(50,50) button1.clicked.connect(showDialog) win.setWindowTitle("Click button") win.show() sys.exit(app.exec_())
|
それでは、showDialog()を見てみましょう。
ダイアログを作成する
ダイアログはで作成されます QMessageBox()。 これをPyQt5からインポートすることを忘れないでください。
1
|
from PyQt5.QtWidgets import QPushButton
|
次に、メソッドを使用します setIcon()、 setText()、 setWindowTitle() 窓の装飾を設定します。
ダイアログボタンは、次のコマンドで構成できます。 setStandardButtons()。
1 2 3 4 5 6 7 8 9 10 11 12
|
def showDialog(): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Information) msgBox.setText("Message box pop up window") msgBox.setWindowTitle("QMessageBox Example") msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msgBox.buttonClicked.connect(msgButtonClick)
returnValue = msgBox.exec() if returnValue == QMessageBox.Ok: print('OK clicked')
|
ダウンロード可能なコード
以下のコードをコピーして自分のコンピューターに貼り付け、どのように機能するかをテストできます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot
def window(): app = QApplication(sys.argv) win = QWidget() button1 = QPushButton(win) button1.setText("Show dialog!") button1.move(50,50) button1.clicked.connect(showDialog) win.setWindowTitle("Click button") win.show() sys.exit(app.exec_()) def showDialog(): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Information) msgBox.setText("Message box pop up window") msgBox.setWindowTitle("QMessageBox Example") msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msgBox.buttonClicked.connect(msgButtonClick)
returnValue = msgBox.exec() if returnValue == QMessageBox.Ok: print('OK clicked') def msgButtonClick(i): print("Button clicked is:",i.text()) if __name__ == '__main__': window()
|
Python PyQtを初めて使用する場合は、 それなら私はこの本を強くお勧めします。
例をダウンロード
Hope this helps!
Source link