PySide (Qt for Python) は、Qt(キュート)の Python バインディングで、GUI などを構築するためのクロスプラットフォームなライブラリです。配布ライセンスは LGPL で公開されています。最新のバージョンは Qt6 に対応した PySide6(記事執筆時点で 6.2.2.1)です。
QDialog クラスを利用すれば、OK とか Cancel ボタン付きのダイアログボックスが簡単にできます。
本記事では、下記の OS 環境を使用しています。
![]() |
Fedora Linux 35 Workstation | x86_64 |
簡単なサンプルを紹介します。ダイアログは modal ウィンドウです。
qt_dialog.py の実行例
qt_dialog.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
import sys | |
from PySide6.QtWidgets import ( | |
QApplication, | |
QDialog, | |
QPushButton, | |
QSizePolicy, | |
QVBoxLayout, | |
QWidget, QDialogButtonBox, QLabel, | |
) | |
class ExampleDlg(QDialog): | |
def __init__(self): | |
super().__init__() | |
self.setWindowTitle('Dialog') | |
self.layout = QVBoxLayout() | |
self.setLayout(self.layout) | |
message = QLabel('ダイアログボックスを表示しました。') | |
self.layout.addWidget(message) | |
dlgbtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel | |
bbox = QDialogButtonBox(dlgbtn) | |
bbox.accepted.connect(self.accept) | |
bbox.rejected.connect(self.reject) | |
self.layout.addWidget(bbox) | |
class Example(QWidget): | |
def __init__(self): | |
super().__init__() | |
self.init_ui() | |
self.setWindowTitle('Dialog Example') | |
def init_ui(self): | |
layout = QVBoxLayout() | |
self.setLayout(layout) | |
btn = QPushButton('ダイアログ表示') | |
btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) | |
btn.clicked.connect(self.button_clicked) | |
layout.addWidget(btn) | |
@staticmethod | |
def button_clicked(): | |
dlg = ExampleDlg() | |
if dlg.exec(): | |
print('OK ボタンがクリックされました。') | |
else: | |
print('Cancel ボタンがクリックされました。') | |
def main(): | |
app = QApplication(sys.argv) | |
ex = Example() | |
ex.show() | |
sys.exit(app.exec()) | |
if __name__ == '__main__': | |
main() |
つい、QWidget でダイアログを作ってしまって、しまったと思うことが多いので、自分のための備忘録として書き留めました。🙇
参考サイト

にほんブログ村
0 件のコメント:
コメントを投稿