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

2024-06-16 11:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打开一个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

Tags: pathself列表def图像格式qtfnameparent
1条回答
网友
1楼 · 发布于 2024-06-16 11:49:27

必须使用data()方法将QByteArray转换为bytes,然后使用decode()将字节转换为string。然后将其串联起来以获得所需的格式。你知道吗

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
)

相关问题 更多 >