QLabel background-color expanding too much
Unsolved
General and Desktop
-
Hi, I've recently started using Qt5 with python, and I'm liking it a lot.
But today I found myself stuck at this problem:
When I set the background color for a QLabel inside a QVBoxLayout, the QLabel takes the whole width of the layout.
I've tried setting the padding and the margin to 0, without luck.Here is my full code:
#!/bin/env python import sys from PyQt5.QtWidgets import * class App(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300,300,350,100) self.setFixedSize(350, 70) self.setWindowTitle("Paladins_Test") self.hbox = QHBoxLayout() self.vbox = QVBoxLayout() self.vbox.addLayout(self.hbox) window = QWidget() window.setObjectName("mainwidget") window.setLayout(self.vbox) self.setCentralWidget(window) self.textbox = QLineEdit(self) self.button = QPushButton("Submit", self) self.button.clicked.connect(self.showTabs) self.textbox.returnPressed.connect(self.button.click) self.hbox.addWidget(self.textbox) self.hbox.addWidget(self.button) def showTabs(self): self.setFixedSize(350, 500) player = self.textbox.text() tabwidget = QTabWidget(self) self.vbox.addWidget(tabwidget) tab1 = QWidget(self) tab1.layout = QVBoxLayout() tab1.setLayout(tab1.layout) tabwidget.addTab(tab1, "Player Info") label1 = QLabel(self) label1.setText(player) label1.setObjectName("playername") label2 = QLabel(self) label2.setText("Level:") label3 = QLabel(self) label3.setText("Wins:" ) label4 = QLabel(self) label4.setText("Losses:" ) label5 = QLabel(self) label5.setText("Region:") tab1.layout.addWidget(label1) tab1.layout.addWidget(label2) tab1.layout.addWidget(label3) tab1.layout.addWidget(label4) tab1.layout.addWidget(label5) tab1.layout.addStretch(1) if __name__ == '__main__': app = QApplication(sys.argv) gui = App() with open('style.qss', 'r') as myfile: qss = myfile.read() app.setStyleSheet(qss) gui.show() sys.exit(app.exec_())
And here's the qss stylesheet:
QLabel { font-size: 20px; } #mainwidget { background-color: lightblue; } #playername { font-size: 30px; margin-top: 15px; background-color: red; border: 1px solid darkred; border-radius: 4px; qproperty-alignment: AlignHCenter; }
Here's a pic:
As you can see, the QLabel's background is too widened.
How can I make it fit the text? -
Hi and welcome to devnet,
From the top of my head, put the QLabel in a QHBoxLayout surrounded by QSpacerItems.