Python 标签中的PyQt5 Pixmap未调整大小

Python 标签中的PyQt5 Pixmap未调整大小,python,pyqt,pyqt5,qlabel,qpixmap,Python,Pyqt,Pyqt5,Qlabel,Qpixmap,我有以下代码,它在3秒钟后更改标签中的pixmap。问题是,当它更改pixmap时,新图像的顶部和底部将被切断,但其大小与前一个图像相同。你知道如何避免这种情况吗 from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget, QHBoxLayout from PyQ

我有以下代码,它在3秒钟后更改标签中的pixmap。问题是,当它更改pixmap时,新图像的顶部和底部将被切断,但其大小与前一个图像相同。你知道如何避免这种情况吗

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_())
第一个像素地图

第二个像素地图

ethernet.png

wifi_no.png


布局具有默认边距,其大小取决于操作系统,例如,在我的例子中是9px,因此作为30 px的“背景”高度,减去上下边距,您将得到剩余的12px,该值小于20px QPixmap的高度,从而使其显示为剪切。在两个QPixmap中都有切口,但在第一个中更明显。解决方案是消除上下页边距:

#。。。
hbox=QHBoxLayout(背景)
l、 t,r,b=hbox.getContentsMargins()
hbox.setContentsMargins(l,0,r,0)
# ...

hbox.setContentsMargins(0,0,0,0)
非常感谢您的解释!我很高兴第二张照片被剪掉了,因为我学到了一些新东西@微笑4如果我的答案对您有帮助,请不要忘记标记为正确,如果您不知道如何做,请检查