I want to define a custom button with label next to it, these two should be combined as a control and there should always be no space between and won't be affected by the layout or other widgets.
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])
However, the label is quite far away from the button control if it is added to the main window within a QHBoxLayout and there is too much space for this custom button. In addition, if I set the alignment of the custom button as center, all of them will be aligned to center, and other alignments work as well. However, this is not exactly what I want, I hope the button and label will always be closely next to each other. Any elegant solutions?
You can add a stretch before the first widget and after the last:
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)
col.setSpacing(0)
# ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.