SmileXS4
SmileXS4

Reputation: 51

PyQt5 Pixmap in Label not resizing

I have the following code, which changes the pixmap in a label after 3 seconds. The problem is that when it changes the pixmap, the top and bottom part of the new image is cut off, but it is the same size as the previous. Do you know how to avoid this?

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_())

first pixmap

second pixmap

ethernet.png

wifi_no.png

Upvotes: 1

Views: 579

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

Layouts have default margins whose size depends on the OS which, for example in my case is 9px, so being the height of the "background" of 30 px and subtracting the upper and lower margins you get a remaining 12px that is less than the height of the 20px QPixmap causing it to appear cut. In both QPixmap there was the cut but it is more noticeable in the first. The solution is to eliminate the upper and lower margins:

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

Upvotes: 1

Related Questions