Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt5: Center align a label

Tags:

This should be really simple but I just can't find an answer for this. I've tried this PyQt4 code:

label.setAlignment(Qt.AlignCenter)

But that gives me no luck.

Thanks

like image 620
Lachlan Avatar asked Sep 03 '14 07:09

Lachlan


People also ask

How to align label in PyQt5?

PyQt5 – alignment() method for Label This method is used too know the type of alignment the label is having. We use setAlignment() method to set the alignment, alignment() method returns the Qt. Alignment object which is the argument of the setAlignment() method.

How do I center a label in Qt?

Create a second label and set it to the center (Qt. AlignVCenter) in vertical direction only. To align in center horizontally, enter At. AlignHCenter.

How do you align labels in python?

Build A Paint Program With TKinter and Python Tkinter Label widget can be aligned using the anchor attributes. In order to calculate the accommodate spacing and alignment of the widget, anchor would help in a better way. Anchor provides several options such as N, W, S, E, NW, NE.

How do I align text in Qlineedit?

Text can be selected with setSelection() or selectAll(), and the selection can be cut(), copy()ied and paste()d. The text can be aligned with setAlignment().


1 Answers

I think the problem may be that the label is centered, but it does not fill the space you think it does. You can verify by changing the label background color. The following example works for me on Windows 7:

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.label = QLabel("Test", self)
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("QLabel {background-color: red;}")

        self.button = QPushButton("Test", self)

        self.layout = QGridLayout()
        self.layout.addWidget(self.label, 0, 0)
        self.layout.addWidget(self.button, 0, 1)

        self.setLayout(self.layout)
        self.show()

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
like image 66
Fenikso Avatar answered Sep 24 '22 05:09

Fenikso