Qt使用綠色pdf閱讀器開啟檔案

朱小勇發表於2024-09-10

1.下載SumatraPDF

2.設定

3.程式碼

void MainWindow::on_pushButton_clicked()
{
    QProcess *process = new QProcess();
    QString filePath = "C:\\Users\\jude\\Desktop\\su\\11.pdf";
    QString sumatraPath = "C:\\Users\\jude\\Desktop\\su\\SumatraPDF-3.5.2-64.exe"; // 請根據實際安裝路徑修改
    // 設定啟動的程式和引數
    QStringList arguments;
    arguments << filePath;

    // 啟動Sumatra PDF
    process->start(sumatraPath, arguments);

    // 等待程序啟動
    if (!process->waitForStarted()) {
        qDebug() << "Failed to start Sumatra PDF.";
        return;
    }

    // 獲取程序的PID
    qint64 pid = process->processId();
    qDebug() << "Sumatra PDF started with PID:" << pid;

    QTimer::singleShot(5000, [process]() {
        qDebug() << "Terminating Sumatra PDF...";
        process->terminate(); // 嘗試優雅地終止程序
        if (!process->waitForFinished(3000)) { // 等待3秒
            qDebug() << "Sumatra PDF did not terminate gracefully. Killing it...";
            process->kill(); // 強制終止程序
            process->waitForFinished(); // 等待程序結束

            delete process;
        }
        qDebug() << "Sumatra PDF closed.";
    });

    qDebug() << "Sumatra PDF finished.";
}

相關文章