简体   繁体   English

带有图像的 Qlabel 使用 QPixmap

[英]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.我想在 Qwidget 中包含一个 QToolbar,但我发现我只能在 QMainWindow 中创建一个 QToolbar。 So, instead I want to create a Qlabel with an arrow icon in it.因此,我想创建一个带有箭头图标的 Qlabel。 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 阈值以更好地显示它们:

已更改 alpha 的图像

Those lines are part of the image and Qt cannot "guess" what portions of the image are "important" to you or not.这些线条是图像的一部分,Qt 无法“猜测”图像的哪些部分对您“重要”与否。
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.只需寻找不同的图像,或通过将其剪切到箭头边框进行编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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