我正在玩 PyQt 中的 QPixmaps。 我想让它们在调整窗口大小时保持相同的纵横比的同时调整大小,但是当我尝试时,我只能使窗口变大,never变小。
为什么会这样,是否有解决方法?
代码如下:
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
class ResizablePixmapWidget(QWidget):
def __init__(self, pixmap: QPixmap, parent=None):
super().__init__(parent)
self.original_pixmap = pixmap
self.pixmap_label = QLabel(self)
self.pixmap_label.setPixmap(self.original_pixmap)
layout = QVBoxLayout(self)
layout.addWidget(self.pixmap_label)
layout.setContentsMargins(0, 0, 0, 0)
def resizeEvent(self, event):
widget_size = self.size()
scaled_pixmap = self.original_pixmap.scaled(widget_size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
self.pixmap_label.setPixmap(scaled_pixmap)
self.pixmap_label.resize(scaled_pixmap.size())
# self.pixmap_label.adjustSize()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Replace 'path_to_image.jpg' with the path of your image file
pixmap = QPixmap("path_to_image.jpg")
resizable_pixmap_widget = ResizablePixmapWidget(pixmap, self)
self.setCentralWidget(resizable_pixmap_widget)
self.setWindowTitle('Resizable QPixmap')
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
我尝试将 QPixmap 应用于自定义 QWidget(如上所示)以及常规 Qlablel。
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Replace 'path_to_image.jpg' with the path of your image file
pixmap = QPixmap("path_to_image.jpg")
scaled_pixmap = pixmap.scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
pixmap_label = QLabel(self)
pixmap_label.setPixmap(scaled_pixmap)
self.setCentralWidget(pixmap_label)
self.setWindowTitle('Resizable QPixmap')
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
我尝试了可用的纵横比模式(KeepAspectRatio、KeepAspectRatioByExpanding 和 KeepAspectRatio)。
在我的实际代码中,我放弃了,只是在调整窗口大小时使用 QPushbutton 手动调整 QPixmap。但这不是很优雅。