LoginSignup
1
0

More than 5 years have passed since last update.

QComboBoxのフォントを変える

Last updated at Posted at 2017-11-13

はじめに

QComboBoxのアイテム要素の種類を可視化するため、
フォントスタイルとテキストカラーを変更を試みました。

英語でも日本語でも、これだという記事が見つからなかったので、忘備録的に残しておきます。

アイテムのフォントとテキストカラーを変える

setItemData で指定します。
フォントは Qt.FontRole、テキストカラーはQt.ForegroundRoleで指定できます。

    combo = QComboBox(w)
    combo.addItem("Normal")
    font = QFont()
    font.setItalic(False)  # 指定しないと、ComboBox のフォントに引っ張られる
    combo.setItemData(0, font, Qt.FontRole)
    combo.addItem("BlueItalic")
    font = QFont()
    font.setItalic(True)
    combo.setItemData(1, font, Qt.FontRole)
    combo.setItemData(1, QBrush(Qt.blue), Qt.ForegroundRole)

※ イタリックにしない場合は、setItalic(False)を指定します。指定しない場合、以下で説明するコンボボックスのフォントに影響されます。

コンボボックスのフォントとテキストカラーを変える

アイテムの指定だけでは、選択中のアイテムのフォントとテキストカラーは変わりません。
そこで、currentIndexChangedシグナルを活用して、選択変更時に切り替えます。

class ComboBox(QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setObjectName("comboBox")
        self.currentIndexChanged[int].connect(self.__on_currentIndexChanged)

    @pyqtSlot(int, name="on_comboBox_currentIndexChanged")
    def __on_currentIndexChanged(self, index):
        # setStyleSheetで指定。item のテキストカラーには干渉しない
        # フォントはsetItemDataされていれば、干渉されない
        font = self.itemData(index, Qt.FontRole)
        fontStyle = 'italic' if font and font.italic() else 'normal'
        brush = self.itemData(index, Qt.ForegroundRole)
        color = "#{0:06x}".format(brush.color().rgb() if brush else 0)
        styleSheet = "ComboBox { font-style: " + fontStyle + "; color: " + color + "; }"
        self.setStyleSheet(styleSheet)
1
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
1
0