【问题标题】:PyQt5 Pixmap in Label not resizing标签中的PyQt5 Pixmap未调整大小
【发布时间】:2020-04-26 13:22:56
【问题描述】:

我有以下代码,它会在 3 秒后更改标签中的像素图。问题是当它改变像素图时,新图像的顶部和底部被截断了,但它与之前的大小相同。你知道如何避免这种情况吗?

from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget, QHBoxLayout
from PyQt5.QtGui import QImage, QPalette, QBrush, QTransform
from PyQt5.QtCore import QSize

import sys
from datetime import datetime


PictureEthernet = 'E:\\ethernet.png'
PictureWifi0 = 'E:\\wifi_no.png'


class TopBar(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # NETWORK PICTURE
        self.labelNetwork = QtWidgets.QLabel()

        self.pictureNetwork = QtGui.QPixmap(PictureEthernet)
        self.pictureNetwork = self.pictureNetwork.scaled(20, 20, QtCore.Qt.IgnoreAspectRatio)
        self.labelNetwork.setPixmap(self.pictureNetwork)

        # BACKGROUND
        background = QtWidgets.QWidget(self)
        background.setStyleSheet("background-color: gray;")
        background.setGeometry(0, 0, 480, 30)

        # LAYOUT
        hbox = QHBoxLayout(background)
        hbox.addWidget(self.labelNetwork)


        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(3000)
        self.timer.timeout.connect(self.updateImage)
        self.timer.start()

        self.show()

    def updateImage(self):
        self.pictureNetwork = QtGui.QPixmap(PictureWifi0)
        self.pictureNetwork = self.pictureNetwork.scaled(20, 20, QtCore.Qt.KeepAspectRatio)
        self.labelNetwork.setPixmap(self.pictureNetwork)


if __name__=='__main__':
    app = QApplication(sys.argv)
    ex = TopBar()
    sys.exit(app.exec_())

第一个像素图

第二个像素图

以太网.png

wifi_no.png

【问题讨论】:

  • hbox.setContentsMargins(0, 0, 0, 0)

标签: python pyqt pyqt5 qlabel qpixmap


【解决方案1】:

布局具有默认边距,其大小取决于操作系统,例如在我的情况下为 9px,因此“背景”的高度为 30 像素并减去上边距和下边距,剩下的 12px 小于比 20px QPixmap 的高度导致它看起来被切割。在两个 QPixmap 中都有删减,但在第一个中更明显。解决办法是去掉上下边距:

# ...
hbox = QHBoxLayout(background)
l, t, r, b = hbox.getContentsMargins()
hbox.setContentsMargins(l, 0, r, 0)
# ...

【讨论】:

  • 非常感谢您的解释!我很高兴第二张图片被剪掉了,因为我学到了一些新东西!
  • @SmileXS4 如果我的回答对您有帮助,请不要忘记标记为正确,如果您不知道该怎么做,请查看tour
猜你喜欢
  • 1970-01-01
  • 2022-07-07
  • 2017-09-20
  • 2014-10-14
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多