0


Qt如何读取.txt文件(将内容读到文本编辑框)

文章目录

一、单独作为一个简单的项目(可以占用QMainWindow)

在这里插入图片描述

//LogWidget.h (mainwindow.h)

#ifndefLogWidget_H#defineLogWidget_H#include<QMainWindow>#include<QDebug>#include<QFile>namespace Ui {classLogWidget;}classLogWidget:publicQMainWindow{
    Q_OBJECT

public:explicitLogWidget(QWidget *parent =0);~LogWidget();private slots://槽函数voidon_pushButton_clicked();private:
    Ui::LogWidget *ui;};#endif// LogWidget_H

//LogWidget.cpp (mainwindow.cpp)

#include"LogWidget.h"#include"ui_LogWidget.h"//uic工具自动由xx.ui生成ui_xxx.h//构造函数LogWidget::LogWidget(QWidget *parent):QMainWindow(parent),ui(new Ui::LogWidget){
    ui->setupUi(this);}//析构函数LogWidget::~LogWidget(){delete ui;}voidLogWidget::on_pushButton_clicked(){
    QString displayString;
    QFile file("C:\\Users\\zwc11\\Yeecoh\\log.txt");//目标文件路径if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){qDebug()<<"Can't open the file!";}while(!file.atEnd()){
        QByteArray line = file.readLine();
        QString str(line);qDebug()<< str;
        displayString.append(str);}
       ui->textEdit->clear();
       ui->textEdit->setPlainText(displayString);}

//LogWidget.ui (xml格式) (mainwindow.ui)

<?xml version="1.0" encoding="UTF-8"?><uiversion="4.0"><class>LogWidget</class><widgetclass="QMainWindow"name="LogWidget"><propertyname="geometry"><rect><x>0</x><y>0</y><width>1179</width><height>640</height></rect></property><propertyname="windowTitle"><string>LogWidget</string></property><widgetclass="QWidget"name="centralWidget"><widgetclass="QTextEdit"name="textEdit"><propertyname="geometry"><rect><x>10</x><y>90</y><width>1151</width><height>491</height></rect></property></widget><widgetclass="QPushButton"name="pushButton"><propertyname="geometry"><rect><x>390</x><y>20</y><width>301</width><height>51</height></rect></property><propertyname="text"><string>读取日志</string></property></widget></widget><widgetclass="QMenuBar"name="menuBar"><propertyname="geometry"><rect><x>0</x><y>0</y><width>1179</width><height>22</height></rect></property></widget><widgetclass="QToolBar"name="mainToolBar"><attributename="toolBarArea"><enum>TopToolBarArea</enum></attribute><attributename="toolBarBreak"><bool>false</bool></attribute></widget><widgetclass="QStatusBar"name="statusBar"/></widget><layoutdefaultspacing="6"margin="11"/><resources/><connections/></ui>

// fileRead.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION,4): QT += widgets

TARGET = fileRead            //.pro文件名
TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += main.cpp\
        LogWidget.cpp

HEADERS  += LogWidget.h

FORMS    += LogWidget.ui

//main.cpp

#include"LogWidget.h"#include<QApplication>intmain(int argc,char*argv[]){
    QApplication a(argc, argv);
    LogWidget w;
    w.show();return a.exec();}

二、大项目中作为菜单栏的一个功能(只能用QDialog)

//LogWidget.h

#ifndefLogWidget_H#defineLogWidget_H#include<QDialog>#include<QDebug>#include<QFile>namespace Ui {classLogWidget;}classLogWidget:publicQDialog//区别只有这里换成继承自QDialog类{
    Q_OBJECT

public:explicitLogWidget(QWidget *parent =0);~LogWidget();private slots:voidon_pushButton_clicked();private:
    Ui::LogWidget *ui;};#endif// LogWidget_H

//LogWidget.cpp

#include"LogWidget.h"#include"ui_LogWidget.h"LogWidget::LogWidget(QWidget *parent):QDialog(parent),//区别就是这里换成QDialogui(new Ui::LogWidget){
    ui->setupUi(this);}LogWidget::~LogWidget(){delete ui;}voidLogWidget::on_pushButton_clicked(){
    QString displayString;
    QFile file("C:\\Users\\zwc11\\Yeecoh\\log.txt");if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){//qDebug()<<"Can't open the file!";   //如果qDebug()内容一边写入log.txt,一边读取到文件末尾,则会死循环不停地写入}//日志文件会在几秒里扩充到上百MBwhile(!file.atEnd()){
        QByteArray line = file.readLine();
        QString str(line);//qDebug()<< str;                
        displayString.append(str);}
       ui->textEdit->clear();
       ui->textEdit->setPlainText(displayString);}

//LogWidget.ui:与上文完全相同

//YeecohWindow.cpp (mainwindow.cpp)

voidYeecohWindow::log(){
    QString fileName =QFileDialog::getOpenFileName(this,tr("打开详细日志"),//打开文件窗口名称"C:\\Users\\zwc11\\Yeecoh",//默认搜索路径tr("txt(*.txt);;All files(*.*)"));//过滤器if(fileName.isEmpty()){QMessageBox::warning(this,"Warning!","Failed to open the log.txt !     ");}else{//重点设计一下这里
        LogWidget win;
        win.exec();}}

更新:
LogWidget.cpp

//add by Edward,2022-06-25#include"LogWidget.h"#include"ui_LogWidget.h"#include<QStandardPaths>LogWidget::LogWidget(QWidget *parent):QDialog(parent),ui(new Ui::LogWidget){
    ui->setupUi(this);}LogWidget::~LogWidget(){delete ui;}voidLogWidget::on_pushButton_clicked(){
    QString displayString;//QFile file("C:/Users/zwc11/Yeecoh/log.txt");  //调试用,工位绝对路径,//QFile file("%HOMEPATH%/Yeecoh/log,txt");      //调试用,使用家目录环境变量,读取失败//QFile file(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/Yeecoh/log.txt"); //旧写法,选择要读取的文件(使用Qt家目录语法)
    QFile file(QCoreApplication::applicationDirPath()+"/Yeecoh/log.txt");//新写法,选择要读取的文件,add by Edward,2022-07-01if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){//qDebug()<<"Can't open the file!";}while(!file.atEnd()){
        QByteArray line = file.readLine();
        QRegExp rx("(.*Debug.*)|(.*Info.*)|(.*Warning.*)|(.*Critical.*)|(.*Fatal.*)");
        QString str(line);if(rx.exactMatch(str)){//判断目标与正则表达式是否匹配//qDebug()<< str;
            displayString.append(str);}else{//什么也不做,不显示内容}}
       ui->textEdit->clear();
       ui->textEdit->setPlainText(displayString);}

日志优化:去除读取文件的按钮,去除右上角?按钮
LogWidget.cpp

//add by Edward,2022-06-25#include"QMainWindow"#include"LogWidget.h"#include"ui_LogWidget.h"#include<QStandardPaths>LogWidget::LogWidget(QWidget *parent):QDialog(parent),ui(new Ui::LogWidget){
    ui->setupUi(this);this->setWindowFlags(Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint);//把QMenubar右上角的?按钮隐藏,add by Edward,2022-08-03
    QString displayString;//QFile file(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/Yeecoh/log.txt"); //旧写法,选择要读取的文件(使用Qt家目录语法)//QFile file(QCoreApplication::applicationDirPath()+"/Yeecoh/log.txt");//新写法,选择要读取的文件,add by Edward,2022-07-01#ifdefWIN32
    QFile file(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/AppData/Local/Yeecoh/log.txt");//动态数据不能放在C盘ProgramFiles下,将Yeecoh目录放在隐藏目录AppData/Local下,add by Edward,2022-08-02#else
    QFile file(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/Yeecoh/log.txt");//动态数据放在home/用户名/目录下,add by Edward,2022-08-03#endifif(!file.open(QIODevice::ReadOnly | QIODevice::Text)){//qDebug()<<"Can't open the file!";}while(!file.atEnd()){
        QByteArray line = file.readLine();
        QRegExp rx("(.*Debug Message.*)|(.*Info Message.*)|(.*Warning Message.*)|(.*Critical Message.*)|(.*Fatal Message.*)");//过滤规则
        QString str(line);if(rx.exactMatch(str)){//判断目标与正则表达式是否匹配//qDebug()<< str;
            displayString.append(str);}else{//正则匹配条件不符合,则什么也不做,不显示内容}}
       ui->textEdit->clear();
       ui->textEdit->setPlainText(displayString);}LogWidget::~LogWidget(){delete ui;}
标签: qt

本文转载自: https://blog.csdn.net/Edward1027/article/details/125463999
版权归原作者 程序员爱德华 所有, 如有侵权,请联系我们删除。

“Qt如何读取.txt文件(将内容读到文本编辑框)”的评论:

还没有评论