我目前正在做一些基本的练习。我正在尝试重写一些应用程序,其中我使用 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_()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
在尝试使用 Python 和 PyQt5 时,我遇到了一个问题。我的 GUI 中有一些标签(QLabel)和图像(QPixmap),我想在它们上画一些东西,具体取决于主程序的功能。我不知道怎么办。例如,我从 BinColUI 类调用 setLabels() 更改标签上的文本,然后我想在它们上绘制一些内容(即 QPainter.drawLine())。我尝试过的方法不起作用,没有绘制任何内容。我不成功的尝试在 setLabels() 中被注释掉。我该怎么做?
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget
class BinColUI(QMainWindow):
def __init__(self):
super().__init__()
self.initUi()
self.createLabelTop()
self.createLabelBot()
def initUi(self):
self.setWindowTitle('Bin Collection')
self.setFixedSize(500, 500)
# self.setStyleSheet('background-color: white')
self.generalLayout = QVBoxLayout()
self._centralWidget = QWidget(self)
self.setCentralWidget(self._centralWidget)
self._centralWidget.setLayout(self.generalLayout)
def paintEvent(self, event):
self.qp = QPainter()
self.qp.begin(self)
self.drawLine(event, self.qp)
self.qp.end()
def drawLine(self, event, qp):
pen = QPen(Qt.red, 3, Qt.SolidLine)
qp.setPen(pen)
qp.drawLine(5, 5, …Run Code Online (Sandbox Code Playgroud)