我想用所有支持的图像格式打开一个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
你必须使用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
)