我想定义一个带有标签的自定义按钮,这两个按钮应合并为控件,并且它们之间始终不应有空格,并且不受布局或其他小部件的影响。
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])
但是,如果将标签添加到QHBoxLayout的主窗口中并且该自定义按钮有太多空间,则该标签与按钮控件相距很远。另外,如果我将自定义按钮的对齐方式设置为中心,则所有对齐方式都将对齐到中心,其他对齐方式也可以使用。但是,这并不是我想要的,我希望按钮和标签将始终紧靠彼此。有什么优雅的解决方案吗?
答案 0 :(得分:0)
您可以在第一个小部件之前添加一个拉伸,而在最后一个小部件之后添加一个拉伸:
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()
# ...