Skip to content Skip to sidebar Skip to footer

How To Customise Qgroupbox Title In Pyqt5?

Here's a piece of code that creates a simple QGroupBox: from PyQt5.QtWidgets import (QApplication, QWidget, QGroupBox, QGridLayout) class QGroupBoxTes

Solution 1:

1) Probably that's the default QT placement, in the first image the platform style is used, and its take care of borders and title placement, when you change the stylesheet you override something and you get the ugly placement.

2) You can control the "title" position using the QGroupBox:title controls, for example:

gb.setStyleSheet('QGroupBox:title {''subcontrol-origin: margin;''subcontrol-position: top center;''padding-left: 10px;''padding-right: 10px; }')

will result in something like this:

title

3) My suggestion is to create different strings for the stylesheet attributes you want to change, then compose them to create the style you want.

Solution 2:

Even though this question has already been answered, I will post what I've figured out regarding technics of applying style sheets to widgets in PyQt which partly answers my original question. I hope someone will find it useful.

I think it's nice to keep the styles in separate css(qss) files:

/*css stylesheet file that contains all the style information*/

QGroupBox {
  border: 1px solid black;
  border-radius: 5px;
}

QGroupBox:title{
  subcontrol-origin: margin;
  subcontrol-position: top center;
  padding: 03px03px;
}

and the python code looks like this:

from PyQt5.QtWidgets import (QApplication, QWidget,
                             QGroupBox, QGridLayout)
from PyQt5.QtCore import QFile, QTextStream

class QGroupBoxTest(QWidget):
  def __init__(self):
    super().__init__()
    self.initUI()

  def initUI(self):
    gb = QGroupBox()
    gb.setTitle('QGroupBox title:')

    gb.setStyleSheet(self.getStyleSheet("./styles.qss"))

    appLayout = QGridLayout()
    appLayout.addWidget(gb, 0, 0)
    self.setLayout(appLayout)

    self.setWindowTitle('QGroupBox test window')
    self.setGeometry(300, 300, 300, 300)

  def getStyleSheet(self, path):
    f = QFile(path)
    f.open(QFile.ReadOnly | QFile.Text)
    stylesheet = QTextStream(f).readAll()
    f.close()
    return stylesheet

if __name__ == "__main__":

  import sys

  app = QApplication(sys.argv)
  test = QGroupBoxTest()
  test.show()

  sys.exit(app.exec_())

which yields the following output:

qgb-1.jpg

Post a Comment for "How To Customise Qgroupbox Title In Pyqt5?"