如何在PyQt5中自定义QGroupBox标题? [英] How to customise QGroupBox title in PyQt5?

查看:1701
本文介绍了如何在PyQt5中自定义QGroupBox标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一段代码,它创建了一个简单的QGroupBox:

Here's a piece of code that creates a simple QGroupBox:

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

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

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

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

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

if __name__ == "__main__":

  import sys

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

  sys.exit(app.exec_())

这是我的输出结果:

现在让我们说要添加一些样式,可以通过将以下行添加到initUI方法中来实现:

Now let's say I want to add some style to it and I do this by adding this line to the initUI method:

gb.setStyleSheet("border: 1px solid gray; border-radius: 5px")

这是输出:

从图片中可以清楚地看到,标题已结束在框架内,现在与框架边框重叠.

As can be clearly seen from the pic, the title has ended up inside the frame and now is overlapping the frame border.

所以我实际上有三个问题:

So I have three questions actually:

  1. 标题为何移动?
  2. 如何移动它并将其放置在我想要的任何地方(如果可能)?
  3. 如果我仅想舍入边框角而没有指定border-style属性,该怎么办.假设我希望边框样式保持与第一个图片相同,但带有圆角.我该怎么办?

推荐答案

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)您可以使用QGroupBox:title控件来控制标题"位置,例如:

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; }')

将导致如下所示:

3)我的建议是为要更改的样式表属性创建不同的字符串,然后组合它们以创建所需的样式.

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.

这篇关于如何在PyQt5中自定义QGroupBox标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆