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

查看:27
本文介绍了如何在 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. 如果我只是想在不指定边框样式属性的情况下修整边框角怎么办.假设我希望边框样式与第一张图片中的一样,但带有圆角.我该怎么做?

推荐答案

1) 可能这是默认的 QT 布局,在第一张图片中使用了平台样式,并处理了边框和标题位置,当您更改样式表时,您会覆盖某些内容,并且会得到丑陋的位置.

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控件控制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天全站免登陆