PyQt5入門 PythonでGUI作成 - yu00’s blog
- リファレンス:Qt 5.5 > Qt Widgets > The Style Sheet Syntax - スタイルシート詳細
- リファレンス2:Qt 5.5 > Qt Widgets > Qt Style Sheets Reference - プロパティ一覧,サブコントロール一覧など
スタイルシートについて詳細を説明します.
スタイルシートの設定
アプリケーション全体に同じスタイルを設定するには
QApplication.setStyleSheet(),
特定のウィジェットとその子ウィジェットにスタイルを
設定するにはQWidget.setStyleSheet()を使います.
次はアプリケーション全体のQPushButtonの
文字色を赤にする例です.
#! /usr/bin/python3 # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton if __name__ == '__main__': app = QApplication(sys.argv) style = 'QPushButton{color: red}' app.setStyleSheet(style) window = QWidget() button = QPushButton('button', window) window.show() sys.exit(app.exec_())
スタイルの書き方
スタイルはselector, property, valueを指定します.
# selector{property: value} style = 'QPushButton{color: red}'
複数のクラスに同じ設定をしたいときは,
コンマ(,)で区切ります.
style = 'QPushButton, QLabel{color: red}'
クラスごとに設定するには次のようにします.
style = ''' QPushButton{color: red} QLabel{color: blue} '''
複数のプロパティを設定するには
セミコロン(;)で区切ります.
style = ''' QPushButton{ color: red; font-size: 15pt; } '''
スタイルを適用する範囲を指定
セレクターでスタイルを適用する範囲を指定できます.
# すべてのウィジェット style = '*{color: red}' # QPushButtonとその派生クラスのインスタンス style = 'QPushButton{color: red}' # (QPushButton.flat==false)となるインスタンス style = 'QPushButton[flat="false"]{color: red}' # QPushButtonのインスタンスのみ.派生クラスは適用しない style = '.QPushButton{color: red}' # QPushuButtonでobject nameがmyButtonとなるインスタンス style = 'QPushButton#myButton{color: red}' button = QPushButton('button') button.setObjectName('myButton') # QDialogの子孫(子,孫...)のQPushButtonのインスタンス style = 'QDialog QPushButton{color: red}' # QDialogの子のQPushButtonのインスタンス style = 'QDialog > QPushButton{color: red}'
セレクターの組み合わせ
セレクタを組み合わせて使うことができます.
# object nameがmyWidgetの子のウィジェットすべて style = 'QWidget#myWidget > *{color: red}'
Sub-Controls
ウィジェットによっては,サブコントロールを持つ
ものもあります.
サブコントロールのスタイルはコロンコロン(::)で指定します.
例えばQComboBoxのサブコントロールに
下ボタンがあります.
QComboBoxの下ボタンはdrop-downで指定します.
style = 'QComboBox::drop-down{image: url(my-drop-down.png)}'
Pseudo-States
ウィジェットによっては,pseudo-states(疑似状態)を持つものが
あります.
pseudo-statesはコロン(:)で指定します.
例えばQPushBottonのpseudo-statesに
マウスのカーソルが乗っている状態があります.
マウスのカーソルが乗っている状態はhoverで指定します.
style = 'QPushButton:hover{color: red}'
エクスクラメーション(!)はNOTを表します.
次は,マウスが乗っていないとき文字色が赤になります.
style = 'QPushButton:!hover{color: red}'
pseudo-statesをつなげるとANDになります.
次は,マウスが乗っているかつ押されているときに文字色が赤になります.
style = 'QPushButton:hover:pressed{color: red}'
コンマ(,)はORを表します.
style = 'QPushButton:hover, QPushButton:pressed{color: red}'
また,サブコントロールと一緒に使うこともできます.
style = 'QComboBox::drop-down:hover{image: url(my-drop-down.png)}'