QFileDialog为所有支持的图像格式创建过滤器

问题描述 投票:1回答:1

我想用所有支持的图像格式打开一个QFileDialog.getOpenFileName(我可以用来实例化QIcon的所有文件类型)

我已经知道我可以使用QImageReader.supportedImageFormats()获得所有支持的图像格式。

令我困惑的是QImageReader.supportedImageFormats()返回QBytesArray的列表,我不知道如何将其简单地转换为str列表。

class ProfileImageButton(qt.QToolButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setIconSize(qt.QSize(100, 100))
        self.clicked.connect(self._onClick)
        self._icon_path = None

    def _onClick(self, checked):
        supportedFormats = qt.QImageReader.supportedImageFormats()
        print([str(fo) for fo in supportedFormats])
        # this prints: ["b'bmp'", "b'cur'", "b'gif'", "b'icns'", "b'ico'", "b'jpeg'",

        fname, filter_ = qt.QFileDialog.getOpenFileName(
            parent=self,
            caption="Load a profile picture",)
            # filter=???????????)   #     <--- TODO

        if fname:
            self.setIcon(qt.QIcon(fname))
            self.setIconSize(qt.QSize(100, 100))
            self._icon_path = fname

    def iconPath(self):
        return self._icon_path
python pyqt5 pyside2 qbytearray
1个回答
1
投票

你必须使用QByteArray方法将bytes转换为data(),然后使用string将字节转换为decode()。然后它仅连接以获得所需的格式。

text_filter = "Images ({})".format(" ".join(["*.{}".format(fo.data().decode()) for fo in supportedFormats]))

fname, _ = qt.QFileDialog.getOpenFileName(
    parent=self,
    caption="Load a profile picture", 
    filter=text_filter
)
© www.soinside.com 2019 - 2024. All rights reserved.