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

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

在这里插入图片描述

//LogWidget.h (mainwindow.h)

#ifndef LogWidget_H
#define LogWidget_H

#include <QMainWindow>
#include <QDebug>
#include <QFile>

namespace Ui {
class LogWidget;
}

class LogWidget : public QMainWindow
{
    Q_OBJECT

public:
    explicit LogWidget(QWidget *parent = 0);
    ~LogWidget();

private slots:         //槽函数
    void on_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;
}

void LogWidget::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"?>
<ui version="4.0">
 <class>LogWidget</class>
 <widget class="QMainWindow" name="LogWidget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1179</width>
    <height>640</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>LogWidget</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QTextEdit" name="textEdit">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>90</y>
      <width>1151</width>
      <height>491</height>
     </rect>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>390</x>
      <y>20</y>
      <width>301</width>
      <height>51</height>
     </rect>
    </property>
    <property name="text">
     <string>读取日志</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1179</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="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>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    LogWidget w;
    w.show();

    return a.exec();
}



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

//LogWidget.h

#ifndef LogWidget_H
#define LogWidget_H

#include <QDialog>
#include <QDebug>
#include <QFile>

namespace Ui {
class LogWidget;
}

class LogWidget : public QDialog    //区别只有这里换成继承自QDialog类
{
    Q_OBJECT

public:
    explicit LogWidget(QWidget *parent = 0);
    ~LogWidget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::LogWidget *ui;
};

#endif // LogWidget_H

//LogWidget.cpp

#include "LogWidget.h"
#include "ui_LogWidget.h"

LogWidget::LogWidget(QWidget *parent) :
    QDialog(parent),                     //区别就是这里换成QDialog
    ui(new Ui::LogWidget)
{
    ui->setupUi(this);
}

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

void LogWidget::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,一边读取到文件末尾,则会死循环不停地写入
    }                                        //日志文件会在几秒里扩充到上百MB
    while(!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)

void YeecohWindow::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;
}

void LogWidget::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-01
    if(!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
#ifdef WIN32
    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
#endif
    if(!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;
}
  • 7
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员爱德华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值