Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I align centre image on QLabel in PyQt5?

I am currently doing some basic excerises. I'm trying to rewrite some application in which I used tkinter to do the same with PyQt5. Everything works apart from one problem - I have a QLabel containing image and I'm trying to align the image in the center of label but it doesn't want to, image stays aligned to the left. Code below:

from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout, QPushButton, QFileDialog
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QPixmap

app=QApplication([])
window=QWidget()
window.setFixedSize(500,500)

layout=QVBoxLayout()

label_img=QLabel()
label_img.setFixedSize(300, 300)
label_img.setAlignment(Qt.AlignCenter)
image = QFileDialog.getOpenFileName(None,'Select file','D:\_Download', "Image files(*.png *.jpg *.jpeg *.gif)")
imagePath = image[0]
pixmap = QPixmap(imagePath)
pixmap.scaledToHeight(label_img.height(), Qt.SmoothTransformation)
label_img.setPixmap(pixmap)
layout.addWidget(label_img)

window.setLayout(layout)
window.show()
app.setStyle('Fusion')
app.exec_()

What am I doing wrong?

like image 801
cyanidem Avatar asked Nov 01 '25 21:11

cyanidem


1 Answers

The QPixmap is centered on the QLabel, but the problem is that the QLabel is not centered with respect to the window. So you should center the widget by changing to:

layout.addWidget(label_img, alignment=Qt.AlignCenter)
like image 132
eyllanesc Avatar answered Nov 04 '25 11:11

eyllanesc