How to align two widgets more closely? In my code, I want to align QLabel 1 and QLabel 2 more closely (i.e. QLabel 2 aligned just below the QLabel 1, with minimum spacing).
import sys from PyQt5 import QtCore,QtGui,QtWidgets class Layout_sample(QtWidgets.QWidget): def __init__(self): super(). __init__() self.setWindowTitle("Layout Sample") self.vbox = QtWidgets.QVBoxLayout() self.lbl1 = QtWidgets.QLabel("F3") self.lbl2 = QtWidgets.QLabel(u'u2550'+u'u2550') self.vbox.addStretch() self.vbox.addWidget(self.lbl1) self.vbox.addWidget(self.lbl2) self.vbox.addStretch() self.vbox.setSpacing(0) self.setLayout(self.vbox) if __name__ =="__main__": app = QtWidgets.QApplication(sys.argv) mainwindow = Layout_sample() mainwindow.show() sys.exit(app.exec_())
Advertisement
Answer
I assume what you’re trying to achieve is a double underline for the text in the first label. The problem with your example is that the unicode character ═
(U+2550) is centered vertically, so there will always be some fixed space above it. The unicode box-drawing characters don’t include a top-aligned double-underline, so a different approach is needed.
One solution is to use html/css inside the label to draw a double border below the text. This has to be done using a table-cell, because Qt only supports a limited subset of html/css:
underline = """<td style=" border-bottom-style: double; border-bottom-width: 3px; ">%s</td>""" self.lbl1 = QtWidgets.QLabel(underline % 'F3') self.vbox.addStretch() self.vbox.addWidget(self.lbl1) self.vbox.addStretch()