简体   繁体   中英

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?

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, )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM