簡體   English   中英

標簽中的 PyQt5 像素圖未調整大小

[英]PyQt5 Pixmap in Label not resizing

我有以下代碼,它在 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

布局具有默認邊距,其大小取決於操作系統,例如在我的情況下為 9px,因此將“背景”的高度設為 30 px 並減去上下邊距,您將得到小於高度的剩余 12px的 20px QPixmap 導致它出現剪切。 在兩個 QPixmap 中都有刪減,但在第一個中更明顯。 解決辦法是消除上下邊距:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM