LoginSignup
2
0

More than 1 year has passed since last update.

PyQt5のチュートリアルを動かす ➇ QMessageBox

Last updated at Posted at 2021-12-02

はじめに

前回はDialogクラスについてご紹介しました。

今回は,QMessageBoxについてご紹介致します。

QMessageBoxは一般的に使用されるモーダルダイアログで、色々な情報をメッセージ表示しオプションで標準ボタンからユーザーに応答を求める機能があります。

QMessageBoxの主要メソッドまとめ

QMessageBoxクラスに関連する重要なメソッドは以下のようになります。

1:setIcon()

メッセージの重大度に対応する定義済みのアイコンを表示する

Question
Information
Warning
Critical

2:setText()

表示されるメインメッセージのテキストを設定する

3:setInformativeText()

追加情報を表示する

4: setDetailText()

ダイアログに詳細ボタンを表示します。それをクリックするとこのテキストが表示されます

5:setTitle()

ダイアログのカスタムタイトルを表示します

6:setStandardButtons()

表示される標準ボタンのリスト。各ボタンは次のように関連付けられています。

QMessageBox.Ok 0x00000400

QMessageBox.Open 0x00002000

QMessageBox.Save 0x00000800

QMessageBox.Cancel 0x00400000

QMessageBox.Close 0x00200000

QMessageBox.Yes 0x00004000

QMessageBox.No 0x00010000

QMessageBox.Abort 0x00040000

QMessageBox.リトライ 0x00080000

QMessageBox.Ignore 0x00100000

7:setDefaultButton()

ボタンをデフォルトとして設定します。Enterが押されるとクリックされたという信号を出します。

8:setEscapeButton()

エスケープキーが押された場合、ボタンがクリックされたものとして扱われるように設定する

www.DeepL.com/Translator(無料版)で翻訳しました。

デモ

qmessage_box.py
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Show message!")

   b.move(100,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt MessageBox demo")
   w.show()
   sys.exit(app.exec_())

def showdialog():
   msg = QMessageBox()
   msg.setIcon(QMessageBox.Information)

   msg.setText("This is a message box")
   msg.setInformativeText("This is additional information")
   msg.setWindowTitle("MessageBox demo")
   msg.setDetailedText("The details are as follows:")
   msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
   msg.buttonClicked.connect(msgbtn)

   retval = msg.exec_()

def msgbtn(i):
   print ("Button pressed is:",i.text())

if __name__ == '__main__':
   window()

実行すると以下のようなウィンドウが出力されます。

Screenshot from 2021-12-02 12-28-42.png

ボタンを押すと次のようなウィンドウが表示されます。

Screenshot from 2021-12-02 12-28-51.png

そして,OKボタンやCancelボタンを押すと以下のようなメッセージが出力されます。

Screenshot from 2021-12-02 12-46-08.png

プログラム解説

以下でQMessageBoxクラスを作成しています。

msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")

そしてsetStandardButton()で表示したいボタンを設定しています。

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

以下でボタンクリックシグナルに対するスロットを設定しています。

msg.buttonClicked.connect(msgbtn)

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0