簡體   English   中英

PyQt5 自定義按鈕旁邊有一個 label

[英]PyQt5 custom button with a label next to it

我想定義一個自定義按鈕,旁邊有 label,這兩個應該組合為一個控件,並且之間應該始終沒有空格,並且不會受到布局或其他小部件的影響。


class ButtonCtrl(QWidget):
    """ Implemented button control with label and checkable property """
    toggled = pyqtSignal(bool)

    def __init__(self,  label='', func=None, parent=None):
        super().__init__(parent)
        col = QVBoxLayout(self)
        self.text = ['ON', 'OFF']
        self.label = QLabel(label, self)
        self.button = QPushButton('ON', self)
        col.addWidget(self.label)
        col.addWidget(self.button)
        # self.setLayout(col)
        col.setSpacing(0)
        self.setContentsMargins(0,0,0,0)
        self.adjustSize()
        # Defaultly False
        self.button.setCheckable(True)
        self.button.setChecked(False)
        self.button.setStyleSheet('''QPushButton[text='OFF']{ background-color:red; font-weight:bold; font-size: 12pt; font-family: Microsoft YaHei} QPushButton[text='ON']:checked{background-color: green; font-weight:normal}''')

        self.updateStatus(False)
        self.label.setStyleSheet('QLabel {font-size: 14pt; font-weight: bold; font-family: Microsoft YaHei}')
        # self.label.setFont(QFont('Microsoft YaHei', 14,99))
        # self.button.setFont(QFont('Microsoft YaHei', 12, 50))
        self.button.toggled.connect(self.toggled.emit)
        self.toggled.connect(self.updateStatus)
        if func:
            self.toggled.connect(func)

    def setLabel(self, label=''):
        self.label.setText(label)

    def setChecked(self, state):
        self.button.setChecked(state)

    def setStatusText(self, on='ON', off='OFF'):
        self.text = [on, off]
        self.updateStatus(self.button.isChecked())

    def status(self):
        return self.button.isChecked()

    def updateStatus(self, state):
        if state:
            self.button.setText(self.text[0])
        else:
            self.button.setText(self.text[-1])


但是,如果將 label 添加到 QHBoxLayout 內的主 window 中,則與按鈕控件相距甚遠,並且此自定義按鈕的空間太大。 此外,如果我將自定義按鈕的 alignment 設置為中心,它們都將對齊到中心,其他對齊方式也可以。 但是,這並不是我想要的,我希望按鈕和 label 永遠緊挨着。 任何優雅的解決方案?

在此處輸入圖像描述

您可以在第一個小部件之前最后一個小部件之后添加拉伸:


class ButtonCtrl(QWidget):
    """ Implemented button control with label and checkable property """
    toggled = pyqtSignal(bool)

    def __init__(self,  label='', func=None, parent=None):
        super().__init__(parent)
        col = QVBoxLayout(self)
        col.addStretch()
        self.text = ['ON', 'OFF']
        self.label = QLabel(label, self)
        self.button = QPushButton('ON', self)
        col.addWidget(self.label)
        col.addWidget(self.button)
        col.setSpacing(0)
        col.addStretch()
        # ...

暫無
暫無

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

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