Skip to content

Commit 5dfd579

Browse files
committed
Add 03-12-03-03
QFileDialog-默认后缀名、标签文本、目录
1 parent 3bef2a1 commit 5dfd579

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import sys
2+
3+
from PySide6 import QtWidgets
4+
5+
"""
6+
QFileDialog
7+
8+
============================ 默认后缀名 ============================
9+
如果用户保存文件时没有指定其他后缀名,则使用默认后缀名
10+
如果首字符为点(.)则将被移除
11+
12+
.setDefaultSuffix(suffix: str)
13+
.defaultSuffix() -> str
14+
============================ 标签文本 ============================
15+
可以对标签文本设定自定义的文本,详情见附录中QFileDialog.DialogLabel枚举值
16+
17+
.setLabelText(label: QFileDialog.DialogLabel, text: str)
18+
.labelText(label: QFileDialog.DialogLabel) -> str
19+
20+
============================== 目录 ============================
21+
可以指定文件对话框当前显示的目录,或获取当前显示的目录
22+
23+
.setDirectory(directory: str)
24+
.setDirectory(directory: QDir)
25+
.setDirectoryUrl(directory: Qurl)
26+
.directory() -> QtCore.QDir
27+
.directoryUrl() -> QUrl
28+
"""
29+
30+
31+
class MyWidget(QtWidgets.QWidget):
32+
def __init__(self, *args, **kwargs):
33+
super().__init__(*args, **kwargs)
34+
self.dialog = QtWidgets.QFileDialog(self)
35+
self.setup_dialog() # 在展示对话框前先完成配置
36+
self.setup_ui()
37+
38+
def setup_dialog(self) -> None:
39+
"""设置文件对话框"""
40+
41+
self.dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) # 文件对话框用于保存文件
42+
43+
# 默认后缀名
44+
self.dialog.setDefaultSuffix("txt") # 设置默认后缀名
45+
46+
# 标签文本
47+
self.dialog.setLabelText(QtWidgets.QFileDialog.Accept, "保存") # 将Accept按钮文本设置为保存
48+
self.dialog.setLabelText(QtWidgets.QFileDialog.Reject, "取消") # 将Reject标签文本设置为取消
49+
50+
def setup_ui(self) -> None:
51+
"""设置界面"""
52+
53+
self.setWindowTitle("QFileDialog-过滤器")
54+
55+
# 创建其他控件
56+
info_le = QtWidgets.QLineEdit(self)
57+
info_le.setMinimumWidth(600)
58+
browse_btn = QtWidgets.QPushButton("保存文件", self)
59+
info_label = QtWidgets.QLabel(self)
60+
61+
# 连接信号与槽
62+
browse_btn.clicked.connect(self.dialog.open) # type: ignore
63+
self.dialog.fileSelected.connect(lambda path: info_le.setText(path)) # type: ignore
64+
65+
def show_current_dir():
66+
"""在info_label中展示当前所在的目录"""
67+
dir_ = self.dialog.directory().path() # 通过.path()获取str型的路径
68+
info_label.setText(dir_)
69+
70+
self.dialog.currentChanged.connect(show_current_dir) # type: ignore
71+
72+
# 使用布局管理器布局
73+
layout = QtWidgets.QVBoxLayout(self)
74+
layout.addWidget(info_le)
75+
layout.addWidget(browse_btn)
76+
layout.addWidget(info_label)
77+
self.setLayout(layout)
78+
79+
80+
if __name__ == "__main__":
81+
app = QtWidgets.QApplication(sys.argv)
82+
window = MyWidget()
83+
window.show()
84+
sys.exit(app.exec())

0 commit comments

Comments
 (0)