4

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
cyanidem
  • 103
  • 2
  • 9

1 Answers1

8

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)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thank you @eyllanesc, that worked. But in full code (that was just relevant fragment) I had two more widgets, labels with text with code: `label_top=QLabel('PLEASE WAIT') label_top.setAlignment(Qt.AlignCenter) label_top.setStyleSheet("font: 20pt Bahnschrift; background-color: #ffd167; color: black") layout.addWidget(label_top) ` And despite not beign aligned to center of the window, the text displayed centered. Why is label with text behave different to label with image? – cyanidem Jan 19 '20 at 15:59
  • @cyanidem Lord, I only solve the problem shown through the code you provide, if you have other hidden codes it is difficult (often impossible) to help you. – eyllanesc Jan 19 '20 at 16:01
  • @cyanidem As I indicated it is impossible to help you if you put code in the comments(the code looks horrible), if you want help create **a new post** giving the necessary information. I recommend you read [ask], [answer] and pass the [tour] – eyllanesc Jan 19 '20 at 16:03
  • Yeah, I'm trying. Accidental enter posted incomplete comment, sorry. – cyanidem Jan 19 '20 at 16:06
  • I tried to post new question, but "You can only post once every 90 minutes." So it will have to wait a bit. Thanks anyway, @eyllanesc. – cyanidem Jan 19 '20 at 16:20