QProcess::startDetached已弃用,求Windows下启动CMD的替代方案
替代方案:使用QProcess::startDetached重载版本
原代码依赖的QProcess::startDetached(const QString &)已被弃用,Qt6中完全移除,推荐使用拆分程序与参数的重载版本,它能自动处理带空格的路径,无需手动拼接复杂的引号转义字符串。
修改后的代码
void MainWindow::on_actionShowFolderInTerminal(bool isChecked) { Q_UNUSED(isChecked) #if defined(Q_OS_WIN) QString targetPath = m_editor->absPath(); QString program = "cmd"; QStringList arguments; // 按顺序拆分原命令的参数,Qt会自动处理引号和空格 arguments << "/C" << "start" << """" // 对应原命令中start后的空窗口标题 << "cmd" << "/K" << "cd /d" << targetPath; QProcess::startDetached(program, arguments); return; #endif CriticalMessage::exec("Currently this function is supported in Windows only. We'll add support to macOS and Linux as soon as possible"); }
关键说明
- 该重载版本
QProcess::startDetached(const QString &program, const QStringList &arguments)在Qt5和Qt6中均有效,无弃用警告。 - 拆分程序与参数后,Qt会自动为包含空格的路径添加引号,彻底避免原代码中手动拼接字符串时的转义错误。
- 简化Windows宏定义:直接用
Q_OS_WIN即可,无需同时定义多个Windows相关宏。
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

