Skip to content

文件选择与长任务 ​

系统文件对话框(主线程安全)与可取消的进度条。


文件 / 目录选择 ​

python
host.pick_file(title="选择文件", name_filter="所有文件 (*.*)", default_dir="") -> str
host.pick_files(title="选择文件", name_filter="所有文件 (*.*)", default_dir="") -> list[str]
host.pick_folder(title="选择文件夹", default_dir="") -> str
host.pick_save_file(title="保存文件", name_filter="所有文件 (*.*)", default_path="") -> str
  • 内部切到 Qt GUI 线程弹系统对话框;任意线程可调,会阻塞至用户关闭。
  • 取消返回 "" / [],不抛异常。
  • name_filter 形如 "文本 (*.txt *.json);;所有文件 (*.*)"。
  • 需要插件私有配置里的文件路径时:拿到路径后写回插件配置 / KV 即可。

想让用户在设置页点按钮选文件,见 自定义设置页 (config_schema 的 type: "file" 目前没有文件选择控件)。


长任务进度(可取消) ​

python
tid = host.begin_progress(plugin_id, title="批量汉化", total=120.0) -> str
host.update_progress(tid, current=12, message="item.lua") -> bool
host.is_progress_cancelled(tid) -> bool     # 循环内检查,True 则尽快退出
host.end_progress(tid, success=True, message="完成") -> bool
host.cancel_progress(tid) -> bool           # 通常由 UI / 热键触发
host.get_progress(tid) -> dict
  • 前端信号:pluginProgress(task_id, plugin_id, ratio, message, done, cancelled)。
  • total <= 0 表示不确定进度;ratio 范围 0~1。
  • 任务结束后保留约 60 秒供查询,随后自动清理。
  • begin_progress 返回 task_id;拿不到就说明宿主拒绝(例如同插件已有在跑的任务)。

标准写法 ​

python
def action_batch(self, **kwargs):
    tid = self.host.begin_progress(self.id, title="批量处理", total=float(len(items)))
    if not tid:
        return {"ok": False, "error": "已有任务在跑"}
    ok = True
    try:
        for i, it in enumerate(items, 1):
            if self.host.is_progress_cancelled(tid):
                ok = False
                break
            self._process(it)
            self.host.update_progress(tid, current=i, message=it.name)
    finally:
        self.host.end_progress(tid, success=ok,
                               message="完成" if ok else "已取消")
    return {"ok": ok}

要点:

  • is_progress_cancelled() 只在真取消时返回 True,务必在循环里检查——这是唯一的中断点。
  • 循环体要快;单片极慢时把取消粒度做粗一点,别为了响应取消把任务切碎。
  • 动作本身是热键/QML 触发时,建议整段放 self.run_in_background(...),别阻塞 UI。

相关 ​

TransBox - 赋能全人类无界限跨语言交流