[英]PyQt5 - resize label to fill the whole window
from PyQt5 import QtGui, QtCore, QtWidgets
class Window(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.label = QtWidgets.QLabel(self)
self.label.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
self.label.resize(800, 600)
self.label.setContentsMargins(0, 0, 0, 0);
self.pixmap = QtGui.QPixmap("image.jpg")
self.label.setPixmap(self.pixmap)
self.label.setMinimumSize(1, 1)
self.label.installEventFilter(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.label)
def eventFilter(self, source, event):
if (source is self.label and event.type() == QtCore.QEvent.Resize):
self.label.setPixmap(self.pixmap.scaled(
self.label.size(), QtCore.Qt.KeepAspectRatio))
return super(Window, self).eventFilter(source, event)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
window.resize(800, 600)
sys.exit(app.exec_())
這是我的應用程序,我的目標很簡單-在整個窗口中設置圖像,並在窗口調整大小后重新調整大小。
這段代碼可以調整圖像大小,但是標簽不能覆蓋整個窗口,我有那些“邊界”。 如何刪除它們/將標簽調整為窗口大小? 如果這會改變事情,我正在Windows上工作。
那就是我現在得到的效果。
我在PyQt4中解決了該問題,所以我不確定100%是否適用於PyQt5,但我想應該這樣做(可能需要進行一些小的修改,例如,導入PyQt5而不是PyQt4)。
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.label = QtGui.QLabel(self)
self.label.resize(800, 600)
pixmap1 = QtGui.QPixmap("image.png")
self.pixmap = pixmap1.scaled(self.width(), self.height())
self.label.setPixmap(self.pixmap)
self.label.setMinimumSize(1, 1)
def resizeEvent(self, event):
pixmap1 = QtGui.QPixmap("image.png")
self.pixmap = pixmap1.scaled(self.width(), self.height())
self.label.setPixmap(self.pixmap)
self.label.resize(self.width(), self.height())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
window.resize(800, 600)
sys.exit(app.exec_())
對您來說最重要的是resizeEvent
定義。 您可以使用已經定義的self.pixmap
並調整其大小,但是圖像的質量會隨着您使用的調整大小而降低。 因此,最好總是創建縮放到當前Window
width
和height
的新pixmap
。
無需在單獨的QWidget
創建QLabel
。 您可以簡單地繼承QLabel
而不是QWidget
。 它將使您的代碼更加簡單和簡潔:
class MyLabelPixmap(QtWidgets.QLabel):
def __init__(self):
QtWidgets.QLabel.__init__(self)
self.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
self.resize(800, 600)
self.pixmap = QtGui.QPixmap("image.jpg")
self.setPixmap(self.pixmap)
self.installEventFilter(self)
def eventFilter(self, source, event):
if (source is self and event.type() == QtCore.QEvent.Resize):
self.setPixmap(self.pixmap.scaled(self.size()))
return super(Window, self).eventFilter(source, event)
如果您想將MyLabelPixmap
小部件嵌入到QMainWindow
只需添加QMainWindow.__init__
self.myLabelPixmap = MyLabelPixmap()
self.setCentralWidget(self.myLabelPixmap)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.