Search code examples
pythoncenteringpyqt5qmainwindowqlabel

PyQt5 set a QLabel x axis automatically center of the window


How can I set x axis of the QLabel the exact center of the window? I have this example

from PyQt5.QtWidgets import QMainWindow,QApplication,QLabel
from PyQt5 import QtCore
import sys

class cssden(QMainWindow):
    def __init__(self):
        super().__init__()

        self.mwidget = QMainWindow(self)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setFixedSize(700,400)

        self.label = QLabel(self)
        self.label.setText("Center of the window")
        self.label.setStyleSheet("color:green;"
                                       "font: bold 20pt 'Arial'")
        self.label.setGeometry(150,200,300,100)
        self.show()

app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: rgb(30,30,30);border: 2px solid rgb(20,20,20)}")
ex = cssden()
sys.exit(app.exec_())

What to do on self.label.setGeometry so the label will be on the center of the window all the time? Is there a method like setCenter() ?


Solution

  • Use a vertical layout. The label will expand to fill the available space, and the text will be aligned centrally by default:

    from PyQt5.QtWidgets import QWidget, QVBoxLayout
    
    class cssden(QMainWindow):
        def __init__(self):
            super().__init__()
    
            self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
            self.setFixedSize(700,400)
    
            self.label = QLabel(self)
            self.label.setText("Center of the window")
            self.label.setStyleSheet("color:green;"
                                           "font: bold 20pt 'Arial'")
    
            self.label.setAlignment(QtCore.Qt.AlignCenter)        
    
            widget = QWidget(self)
            layout = QVBoxLayout(widget)
            layout.addWidget(self.label)
    
            self.setCentralWidget(widget)
    
            self.show()