Implement QT to open Word document

Click the button to open the Word document through QT, you need to use QProcess, add #include <QProcess> to the program.

code:

.h file

#ifndef SIDEBAR_H
#define SIDEBAR_H

#include <QWidget>
#include <QProcess>
#include <QFileInfo>

namespace Ui {
class SideBar;
}

class SideBar : public QWidget
{
    Q_OBJECT

public:
    explicit SideBar(QWidget *parent = nullptr);
    ~SideBar();


private slots:

    void on_usermanual_clicked();

    void OnFinishProc(int, QProcess::ExitStatus);


private:
    Ui::SideBar *ui;
    QString m_filePath;

};

#endif // SIDEBAR_H

.cpp file

#include "SideBar.h"
#include "ui_SideBar.h"

#include <QProcess>
#include <QMessageBox>

SideBar::SideBar(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SideBar)
{
    ui->setupUi(this);
    //文件路径
    m_filePath = "D:/QTproject/SAR/code/resources/userguide.docx";
}

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

void SideBar::on_usermanual_clicked()
{
    QFileInfo fileInfo(m_filePath);
    if (!fileInfo.exists())
    {
        // 文件不存在,提示用户
        QMessageBox::warning(this, "File not found", "The file 'userguide.docx' was not found.");
    }
    else
    {
        QString program = "\"C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE\"";
        QProcess *proc = new QProcess(this);
        QStringList list;
        list<<QString(m_filePath);
        proc->start(program,list);
        connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnFinishProc(int, QProcess::ExitStatus)));

    }

}

void SideBar::OnFinishProc(int, QProcess::ExitStatus)
{
    QProcess * proc = (QProcess *)sender();
    delete proc;

}

1. The word document is opened by WINWORD.EXE, and its path should be written in QProcess::start;

2. #include <QFileInfo> is used to determine whether the file path exists.

3. When the user closes the word document, the WINWORD.EXE process ends. But the proc variable still exists, and it still occupies a piece of memory. When the WINWORD.EXE process ends, proc will send a signal finished. Use this signal to trigger the slot function OnFinishProc to release the proc.

4. If there is a space in the path of WINWORD.EXE, "\" needs to be added.

Reference article: Qt uses QProcess to start a process instance (open a word document)_qprocess to open a file_Golden Bear Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/weixin_55735677/article/details/130726246