簡體   English   中英

如何在PyQt5中自定義QGroupBox標題?

[英]How to customise QGroupBox title in PyQt5?

這是一段創建簡單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_())

這是輸出對我來說的樣子:

QGB-1.JPG

現在假設我想為它添加一些樣式,我通過將此行添加到initUI方法來實現:

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

這是輸出:

QGB-1.JPG

從圖中可以清楚地看到,標題已經在框架內部結束,現在與框架邊框重疊。

所以我實際上有三個問題:

  1. 標題為什么會移動?
  2. 如何移動它並將其放置在我想要的任何地方(如果可能)?
  3. 如果我只想在不指定邊框樣式屬性的情況下舍入邊角,該怎么辦? 假設我希望邊框樣式與第一張照片保持一致,但帶有圓角。 我怎么做?

1)可能是默認的QT位置,在第一個圖像中使用平台樣式,並且它處理邊框和標題放置,當您更改樣式表時,您覆蓋某些內容並且您獲得了丑陋的位置。

2)您可以使用QGroupBox:title控件控制“標題”位置,例如:

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

將導致這樣的事情:

標題

3)我的建議是為要更改的樣式表屬性創建不同的字符串,然后組合它們以創建所需的樣式。

即使這個問題已經得到解答,我也會發布我已經想到的關於在PyQt中將樣式表應用到小部件的技術,這部分回答了我原來的問題。 我希望有人會發現它很有用。

我認為將樣式保存在單獨的css(qss)文件中是很好的:

/*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: 0 3px 0 3px;
}

並且python代碼如下所示:

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_())

產生以下輸出:

QGB-1.JPG

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM