我有以下代码,它将在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_())
第一张像素图
第二像素图
ethernet.png
wifi_no.png
布局具有默认边距,其默认大小取决于操作系统(例如,在我的情况下为9px),因此,作为“背景”的高度为30 px,减去上下边距后,剩下的12px小于20px QPixmap的高度,导致其被剪切。在两个QPixmap中都有剪切,但在第一个中更明显。解决方案是消除上下边距:
# ...
hbox = QHBoxLayout(background)
l, t, r, b = hbox.getContentsMargins()
hbox.setContentsMargins(l, 0, r, 0)
# ...