简体   繁体   中英

Qlabel with image using QPixmap

I wanted to include a QToolbar in a Qwidget, but I found that I can only create a QToolbar in a QMainWindow. So, instead I want to create a Qlabel with an arrow icon in it. I downloaded an image with transparent background (I suppose). But, in the code, the image is not really transparent as I expected, it looks ugly. Is there any way to show only the arrow without the background. Below is a sample code

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'test'
        self.left = 0
        self.top = 0
        self.width = 300
        self.height = 500
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.table_widget = MyTableWidget(self)
        self.setCentralWidget(self.table_widget)

        self.show()

class MyTableWidget(QWidget):

    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        # Create first tab
        label3 = QLabel()
        pixmap = QPixmap("index2.png")
        smaller_pixmap = pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.FastTransformation)
        label3.setPixmap(smaller_pixmap)        
        label3.mouseReleaseEvent = self.on_click

        self.layout.addWidget(label3)
        self.setLayout(self.layout)

    @pyqtSlot()
    def on_click(self, event):
        print('yes')



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

You are getting an "ugly" image because that image has lines that are partially transparent. I've increased the alpha threshold to better show them:

已更改 alpha 的图像

Those lines are part of the image and Qt cannot "guess" what portions of the image are "important" to you or not.
There's fundamentally no easy way to remove them by code, and even you'd succeed the result would be ugly anyway (some partial transparency is required around the border of the image to keep them smooth) and it wouldn't be worth the effort.

Just look for a different image, or edit it by clipping it to the arrow borders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM