PySide6でメニューとステータスバーのサンプル【QAction】

python コンピュータ
python

メニューとステータスバーのサンプルスクリプトです。

import sys
from PySide6.QtWidgets import (QApplication, QMainWindow)
from PySide6.QtGui import (QAction)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("メニューバーとステータスバーのサンプル")
        # ウィンドウサイズの設定
        self.setGeometry(0, 0, 640, 400)

        # メニューバー
        menubar = self.menuBar()
        # ステータスバー
        self.statusbar = self.statusBar()

        # ファイルメニュー
        file_menu = menubar.addMenu("ファイル(&F)")  # &F は Alt+F でアクセス可能にする

        # テストアクション
        test_action = QAction("テスト(&T)", self)
        # テストアクションと処理の紐づけ
        test_action.triggered.connect(self.test_file)
        # テストアクションメニューに登録
        file_menu.addAction(test_action)

        # 終了アクション
        exit_action = QAction("終了(&X)", self)
        # 終了アクションと処理を紐づけ
        exit_action.triggered.connect(self.close)
        # 終了アクションメニューに登録
        file_menu.addAction(exit_action)

    def test_file(self):
        self.statusbar.showMessage("テストが選択されました。")

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

実行するとメニューが確認できます。

メニューのテストを選択すると、ステータスバーに文字列が表示されます。

コメント