1、电脑环境
系统:Windows10
python版本:3.9.6
Qt版本:Qt Creater 4.11.2(community)
2、整体思路
- 在 Qt Creator 中创建一个新的 Qt Widget Application应用程序项目。
- 在 UI 设计器(mainwind.ui)中添加一个 QLineEdit 控件,用于输入python文件路径,命名为 lineEdit。
- 添加一个 QPushButton 控件,用于触发文本查重操作。命名为Button,文本设置为“Button”。
- 添加一个 QLabel 控件,用于显示输出结果。命名为 label。
- 在在 UI 设计器页面,右键控件label -> 转到槽函数…。此时,在mainwindow.h中会声明一个槽函数on_pushButton_clicked用于传递点击的信号。在mainwindow.cpp文件中,定义on_pushButton_clicked代码来实现按钮单击时的操作。以下是基本代码:
void MainWindow::on_pushButton_clicked()
{
// 获取python文件的路径
QString ScriptPath = ui->lineEdit->text();
// 调用 Python 脚本执行查重操作
QProcess process;
QStringList arguments;
arguments << ScriptPath;
// 如果有其它参数继续传入
// arguments << para1 << para2;
// 需要获取python解释器的路径
QString program = "C:/Program Files/Python39/python.exe";
process.start(program, arguments);
process.waitForFinished();
// 获取脚本的输出结果
QString output = process.readAllStandardOutput();
// 在 label 控件中显示输出结果
ui->label->setText(output);
}
在代码中,从QLineEdit 控件获得python文件路径,使用 QProcess 类来调用 Python 脚本执行输出操作。在脚本执行完毕之后从 QProcess 对象中读取输出结果,并将它们显示到 label 控件中。
- 创建一个 Python 脚本hello.py来实现输出Hello Qt。
import sys
import os
print("Hello Qt")
- 在 GUI 操作界面上点击“构建”按钮,确保程序能够正确编译、构建和运行。在程序运行时,选择要运行的python文件,然后点击“Button”按钮。结果将会显示在 label 控件中。
3、完整代码如下所示
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QProcess>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
// 获取python文件的路径
QString ScriptPath = ui->lineEdit->text();
// 调用 Python 脚本执行查重操作
QProcess process;
QStringList arguments;
arguments << ScriptPath;
// 如果有其它参数继续传入
// arguments << para1 << para2;
// 需要获取python解释器的路径
QString program = "C:/Program Files/Python39/python.exe";
process.start(program, arguments);
process.waitForFinished();
// 获取脚本的输出结果
QString output = process.readAllStandardOutput();
// 在 label 控件中显示输出结果
ui->label->setText(output);
}
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
hello.py
import sys
import os
print("Hello Qt")
4、使用脚本查重两个文件时遇到的问题
- 使用QProcess::start()模块无法运行python脚本。
- 使用QProcess::readAllStandardOutput()读取脚本输出使用label显示中文时乱码。
- (下次再写)