【问题标题】:Using system command in Qt在 Qt 中使用系统命令
【发布时间】:2012-06-03 15:54:39
【问题描述】:

我如何使用system 命令,其中命令是用 QString 编写的?

喜欢:

QString command="chmod -R 777 /opt/QT/examples/code/TestGUI/Data";    
system(command);

编译时出现这个错误:

cannot convert ‘QString’ to ‘const char*’
  for argument ‘1’ to ‘int system(const char*)’

谁能给点建议?

【问题讨论】:

标签: qt


【解决方案1】:

QProcess 类http://doc.qt.io/qt-5/qprocess.html。这是你需要的。

【讨论】:

    【解决方案2】:

    您需要从 QString 中获取原始字符数组。这是一种方法:

    system(command.toStdString().c_str());
    

    【讨论】:

      【解决方案3】:

      使用qPrintable()

      system(qPrintable(command));

      【讨论】:

      • 嘿,谢谢!我不知道qPrintable。一个人每天都会学到一些东西。
      【解决方案4】:

      Ankur Gupta 写道,使用 QProcess 静态函数 (link to description):

      int QProcess::execute ( const QString & program )
      

      在你的情况下:

      QProcess::execute ("chmod -R 777 /opt/QT/examples/code/TestGUI/Data");
      

      【讨论】:

        【解决方案5】:

        要更改权限,您可以使用 QFile 的 setPermissions

        【讨论】:

          【解决方案6】:

          您可以将QString 转换为const char*

          如果您的字符串是 UTF8,那么您可以使用:

          const char* my_command = command.toUtf8().constData() ;
          system(my_command);
          

          如果你的字符串不是 UTF8,那么你可以使用:

          command.toLatin1().constData() ;
          system(my_command);
          

          在这种情况下,第二个就是你想要的。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-03-14
            • 1970-01-01
            • 2013-04-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-27
            相关资源
            最近更新 更多