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).
JavaScript
x
26
26
1
import sys
2
from PyQt5 import QtCore,QtGui,QtWidgets
3
4
class Layout_sample(QtWidgets.QWidget):
5
def __init__(self):
6
super(). __init__()
7
self.setWindowTitle("Layout Sample")
8
self.vbox = QtWidgets.QVBoxLayout()
9
self.lbl1 = QtWidgets.QLabel("F3")
10
self.lbl2 = QtWidgets.QLabel(u'u2550'+u'u2550')
11
12
self.vbox.addStretch()
13
self.vbox.addWidget(self.lbl1)
14
self.vbox.addWidget(self.lbl2)
15
self.vbox.addStretch()
16
17
self.vbox.setSpacing(0)
18
self.setLayout(self.vbox)
19
20
21
if __name__ =="__main__":
22
app = QtWidgets.QApplication(sys.argv)
23
mainwindow = Layout_sample()
24
mainwindow.show()
25
sys.exit(app.exec_())
26
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:
JavaScript
1
9
1
underline = """<td style="
2
border-bottom-style: double;
3
border-bottom-width: 3px;
4
">%s</td>"""
5
self.lbl1 = QtWidgets.QLabel(underline % 'F3')
6
self.vbox.addStretch()
7
self.vbox.addWidget(self.lbl1)
8
self.vbox.addStretch()
9