Nihaal
Nihaal

Reputation: 3

How do I align centre image horizontally in PyQt5?

I'm working on my college project, I want to align an Image to centre Horizontally, I tried many thing but not find solution. Here is my code:

from PyQt5.QtGui import QPalette, QLinearGradient, QColor, QBrush, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys

from PyQt5 import QtGui


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

        self.acceptDrops()
        self.setWindowTitle("Mask Detection")
        self.setWindowIcon(QtGui.QIcon('img.png'))
        self.setGeometry(0, 0, 400, 300)
        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignCenter)
        self.pixmap = QPixmap('PBL.png')
        self.label.setPixmap(self.pixmap)
        self.label.resize(self.pixmap.width(),
                          self.pixmap.height())
        self.show()

App = QApplication(sys.argv)
window = Window()

p = QPalette()
gradient = QLinearGradient(0, 0, 0, 400)
gradient.setColorAt(0.0, QColor(56, 93, 166))
gradient.setColorAt(1.0, QColor(10, 123, 146))
p.setBrush(QPalette.Window, QBrush(gradient))
window.setPalette(p)

sys.exit(App.exec())

Upvotes: 0

Views: 465

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

The alignment is with respect to the geometry of the element itself, and since the geometry of the QLabel has the same size as the QPixmap then it will not make a difference. The solution is to make the geometry of the QLabel be the same as the window and that can be done by setting it in the centralWidget:

self.setCentralWidget(self.label)

Upvotes: 2

Related Questions