簡體   English   中英

如何在 PyQt5 中對齊 QLabel 上的中心圖像?

[英]How do I align centre image on QLabel in PyQt5?

我目前正在做一些基本的練習。 我正在嘗試重寫一些應用程序,其中我使用 tkinter 對 PyQt5 執行相同操作。 除了一個問題之外,一切都正常 - 我有一個包含圖像的 QLabel,我試圖將圖像對齊在標簽的中心,但它不想,圖像保持與左側對齊。 代碼如下:

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_()

我究竟做錯了什么?

QPixmap 以 QLabel 為中心,但問題是 QLabel 沒有相對於窗口居中。 因此,您應該通過更改為使小部件居中:

layout.addWidget(label_img, alignment=Qt.AlignCenter)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM