pythonpyqt5

Alignment in PyQt5


I've been trying to learn PyQt5 and decided to do some small project. I'm trying to make a guessing game, where you type in a value and the program says if it's correct. My problem is that I centered my label in a layout part, so it appears at the center bottom of its container, but I want it to be at the center of the page when the button is clicked. I believe that after the button is clicked, the label appears at the bottom of the page due to main_layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignBottom| Qt.AlignmentFlag.AlignJustify). Here's the code:

import sys
import time

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

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

        #fonts
        QFontDatabase.addApplicationFont("fonts\Evangelie.ttf")
        QFontDatabase.addApplicationFont("fonts\Bebas_Neue_Cyrillic.ttf")
        QFontDatabase.addApplicationFont("fonts\MontserratAlternates-Medium.ttf")
        QFontDatabase.addApplicationFont("fonts\MontserratAlternates-Bold.ttf")
        QFontDatabase.addApplicationFont("fonts\MontserratAlternates-SemiBold.ttf")

        #labels
        self.label = QLabel("Скільки чулувіків має крапка?", self)
        self.line_edit = QLineEdit(self)
        self.button = QPushButton("Відповісти.", self)

        self.initUI()

    def initUI(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        #region main window
        self.setWindowTitle("Guess.")
        self.resize(800,700)
        self.setStyleSheet("background-color: #697565;")
        #endregion

        #region label
        self.label.setFont(QFont("Montserrat Alternates SemiBold", 24))
        self.label.adjustSize()
        self.label.setStyleSheet("margin: 0, 20, 0, 0;" \
                                #"background-color:red;"
                                "color: #ECDFCC;"
                                "font-style: bold;"
                                )
        #endregion

        #region line_edit
        self.line_edit.setFixedSize(200, 80)
        self.line_edit.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.line_edit.setFont(QFont("Montserrat Alternates SemiBold", 20))
        self.line_edit.setStyleSheet("background-color: #181C14;" \
                                    "color: #697565;" \
                                    "border-radius: 15px;" \
                                    "margin: 0,20,0,0;")
        #endregion

        #region button
        self.button.setStyleSheet("border-radius:15px;" \
                                "background-color: #ECDFCC;" \
                                "color: #181C14;")
        self.button.setFixedSize(150,50)
        self.button.setFont(QFont("Montserrat Alternates Medium", 10))
        self.button.clicked.connect(self.on_click)
        #endregion

        #region layout
        main_layout = QVBoxLayout()

        main_layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignBottom| Qt.AlignmentFlag.AlignJustify)
        main_layout.addWidget(self.line_edit, alignment=Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignJustify)
        main_layout.addWidget(self.button, alignment=Qt.AlignmentFlag.AlignJustify | Qt.AlignmentFlag.AlignTop)

        central_widget.setLayout(main_layout)
        #endregion

    #region button clicked
    def on_click(self):
        self._answer = self.line_edit.text()
        print(self._answer)

        if(self._answer == '0'):
            self.label.setText("You won!")
            
            self.line_edit.hide()
            self.button.hide()

            self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)        
    #endregion



    def center(self):
        frame_geometry = self.frameGeometry()
        screen_center = QDesktopWidget().availableGeometry().center()
        frame_geometry.moveCenter(screen_center)
        self.move(frame_geometry.topLeft())

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

I've tried using setAlignment method for a label, but it didn't help.

Any help would be greatly appreciated.

Pic:


Solution

  • In initUI adding a stretch before and after your 3 widgets solves the problem :

            ...
            main_layout.addStretch() # added
            main_layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignBottom| Qt.AlignmentFlag.AlignJustify)
            main_layout.addWidget(self.line_edit, alignment=Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignJustify)
            main_layout.addWidget(self.button, alignment=Qt.AlignmentFlag.AlignJustify | Qt.AlignmentFlag.AlignTop)
            main_layout.addStretch() # added
            ...
    

    The other consequence is you can simplify your alignments just doing :

            ...
            main_layout.addStretch()
            main_layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignHCenter)
            main_layout.addWidget(self.line_edit, alignment=Qt.AlignmentFlag.AlignHCenter)
            main_layout.addWidget(self.button, alignment=Qt.AlignmentFlag.AlignHCenter)
            main_layout.addStretch()
            ...
    

    Now, before to enter 0 then hit the button :

    enter image description here

    and after :

    enter image description here