首页 > 其他分享 >Qt如何读取.txt文件(将内容读到文本编辑框)

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

时间:2022-11-04 14:55:13浏览次数:91  
标签:LogWidget Qt ui file txt include 编辑框 log

一、单独作为一个简单的项目(可以占用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;
}

————————————————
版权声明:本文为CSDN博主「码农爱德华」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Edward1027/article/details/125463999

标签:LogWidget,Qt,ui,file,txt,include,编辑框,log
From: https://www.cnblogs.com/xiaohai123/p/16857769.html

相关文章