如何根据QProcess将窗口设置为活动窗口?

时间:2013-03-30 21:20:51

标签: c++ qt window focus qt5

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QTextStream>
#include <QTime>
#include <QProcess>

bool started = false;
QString path;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->statusBar->showMessage("Waiting for input...");
    QFile file("path.txt");
    if(!file.open(QIODevice::ReadOnly)) {
        QMessageBox::information(0, "Error", file.errorString());
    }
    QTextStream in(&file);
    path = in.readLine();
    file.close();
}

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

void MainWindow::on_pushButton_2_clicked()
{
    qApp->exit();
}

void delay(int n)
{
    QTime dieTime = QTime::currentTime().addSecs(n);
    while(QTime::currentTime() < dieTime)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void MainWindow::on_pushButton_clicked()
{
    if(!started) {
        started = true;

        qint32 waitSecs = ui->plainTextEdit->toPlainText().toInt();
        QTime launchTime = QTime::currentTime().addSecs(waitSecs);

        while(waitSecs > 0) {
            waitSecs = QTime::currentTime().secsTo(launchTime);
            ui->statusBar->showMessage(QString("Waiting %1 seconds to launch BLR launcher.").arg(waitSecs));
            delay(1);
        }

        ui->statusBar->showMessage("Launching BLR launcher!");

        QProcess *process = new QProcess(this);
        process->start(path, QStringList() << "");
    }
}

从上面的代码中可以看到(阅读最后几行),我有一个启动的进程。我想确保启动的窗口(通过该过程)是重点。

我知道有这个功能:http://qt-project.org/doc/qt-4.8/qapplication.html#setActiveWindow

它需要一个QWidget作为参数。也许我需要将QProcess转换为Qwidget?

1 个答案:

答案 0 :(得分:0)

不是直接在调用QProcess :: start时调用可执行文件,而是将其用作操作系统中相关打开命令的参数。

例如,在OSX中我会使用

process->start("open programToRun.app");

如果你在Windows中,我肯定有一个等价的,也许使用:

process->start("cmd programToRun.exe").

Hoep有帮助。