Bootstrap

QProcess 调用cmd命令

1.QProcess

#include <QProcess>

作用:可以用来启动外部程序,并与它们交互。
要启动一个进程,通过调用start()来进行,参数包含程序的名称和命令行参数,参数作为一个QStringList的单个字符串。

QProcess process(this);
    QStringList args;
    args<<"/c"<<"shutdown -s -t "+Time; //其中"/c"不可省略,否则无法解析
    // for(int i=0;i<args.size();i++)
    // {
    //     qDebug()<<args.at(i)<<"";
    // }
    /*void start(const QString &program, const QStringList &arguments, OpenMode mode = ReadWrite);
    *  @param program:执行外部程序的绝对路径;
    */
    process.start("C:/Windows/System32/cmd.exe",args);
    
    process.waitForStarted(500);
    process.waitForFinished(500);

2.example

#include "widget.h"
#include "ui_widget.h"
#include <string>
#include <iostream>
#include <QMenu>
#include <QDebug>
#include <QProcess>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    menu =new QMenu(this);

//    QStyleFactory style;
//    QStringList styles=style.keys();
//    for(int i=0;i<styles.size();i++)
//    {
//        qDebug()<<styles.at(i)<<endl;
//    }

//    QStyle *defualtStyle= style.create(styles.at(2));
//    this->setStyle(defualtStyle);
    this->setStyleSheet(QString("background-color:red"));
    ui->lineEdit->setText("30");
    ui->lcdNumber->setLineWidth(0);
    ui->lineEdit->setPlaceholderText("请输入关机时间(秒)");

    connect(timer,SIGNAL(timeout()),this,SLOT(on_timeout()));

}

Widget::~Widget()
{
    delete ui;
}


void Widget::shutdown()
{
    QString str=ui->lineEdit->text();
    int displaytime=str.toUInt();
    ui->lcdNumber->display(displaytime);
    std::string time=str.toStdString();
    std::string shutdown="shutdown -s -t "+time;
    QString Time=QString::fromLocal8Bit(time.c_str());
    //QString cmd= QString::fromLocal8Bit(shutdown.c_str());
    //qDebug()<<"cmd:"<<cmd<<endl;
    //const char *p=shutdown.c_str();
    QProcess process(this);
    QStringList args;
    if(ui->checkBox->isChecked())
    {
        args<<"/c"<<"shutdown -r -t "+Time;
    }
    else {
        args<<"/c"<<"shutdown -s -t "+Time;
    }
    for(int i=0;i<args.size();i++)
    {
        qDebug()<<args.at(i)<<"";
    }
    process.start("C:/Windows/System32/cmd.exe",args);
    process.waitForStarted(500);
    process.waitForFinished(500);
    //system(p);
    //process.kill();
}

void Widget::on_timeout()
{
    double num=ui->lcdNumber->value();
    num--;
    if(0==num)
    {
        timer->stop();
    }
    QString str_=QString::number(num);
    ui->lcdNumber->display(str_);

}


void Widget::on_pushButton_clicked()
{
    shutdown();
    timer->start(1000);
}

void Widget::on_pushButton_2_clicked()
{
    //system("shutdown -a");
    QProcess process(this);
    QStringList args;
    args<<"/c"<<"shutdown -a";
    process.start("C:/Windows/System32/cmd.exe",args);
    process.waitForStarted(500);
    process.waitForFinished(500);
    //process.kill();
    timer->stop();
    close();
}

3.?

为什么打包后,执行出错?

;