文章目录

  • 一、单独作为一个简单的项目(可以占用QMainWindow)
  • 二、大项目中作为菜单栏的一个功能(只能用QDialog)

一、单独作为一个简单的项目(可以占用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_OBJECTpublic: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 guigreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = fileRead            //.pro文件名
TEMPLATE = appDEFINES += QT_DEPRECATED_WARNINGSSOURCES += main.cpp\LogWidget.cppHEADERS  += LogWidget.hFORMS    += 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_OBJECTpublic: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),                     //区别就是这里换成QDialogui(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,一边读取到文件末尾,则会死循环不停地写入}                                        //日志文件会在几秒里扩充到上百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)

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-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-03QString 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 WIN32QFile file(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/AppData/Local/Yeecoh/log.txt");//动态数据不能放在C盘ProgramFiles下,将Yeecoh目录放在隐藏目录AppData/Local下,add by Edward,2022-08-02
#elseQFile 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如何读取.txt文件(将内容读到文本编辑框)相关推荐

  1. python删除重复值所在的行数_使用python读取txt文件的内容,并删除重复的行数方法...

    注意,本文代码是使用在txt文档上,同时txt文档中的内容每一行代表的是图片的名字. #coding:utf-8 import shutil readDir = "原文件绝对路经" ...

  2. python读取txt文件特定内容,并绘制折线图

    本文内容参考以下博文并作出改动:python学习--读取txt文件数据并画图_知北行的博客-CSDN博客_对每个txt的语调变量画图 原始数据: [epoch: 0] train_loss: 1.11 ...

  3. java 读取文件内容_Java如何读取txt文件的内容?

    这个并不困难,大概的步骤是这样的: TXT是一个文本文件,一般采用流的方式读取: java提供了一个FileInputStream,我们可以直接以文件路径构造这个流,也可以以文件对象构造他,如:Fil ...

  4. Java如何读取txt文件的内容?

    作者:子谦 链接:https://www.zhihu.com/question/67344572/answer/252403722 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载 ...

  5. qt文件逐行读取_qt读取txt文件并绘图 qt逐行读取txt文件

    qt中怎么把txt文件读入并存入二维数组? Fopen函数打开要读取的文本,获取文件的文件描述符,并使用fscan()函数读取文件.把它放在二维数组中,就是读取相应格式的数据,然后对应二维数组的每个位 ...

  6. python 读取excel文件,并读成数据框格式输出

    pandas直接读取 import pandas as pd df = pd.read_excel('/path/file.xlsx' ) sheet_name: str, int, list, or ...

  7. c# 逐行写txt_c# 如何逐行读取txt文件的内容

    (函数名凭记忆写的,可能不准确,但差不多) string = File.ReadAll(filename); 获得整个文本 string[] = File.ReadLines(filename); 获 ...

  8. java读取txt文件内容 小白教程

    磁盘I/O 典型I/O读写磁盘工作原理如下: tips: DMA:全称叫直接内存存取(Direct Memory Access),是一种允许外围设备(硬件子系统)直接访问系统主内存的机制.基于 DMA ...

  9. java解析txt文本文件_java读取文本文件内容方法详解,java如何读取txt文件?

    你知道java读取文本文件内容方式都有哪些吗?下面要给大家分享的就是比较简单的方法,一起来了解一下吧. 如何使用java实现读取TXT文件里的内容的方法以及思路: 下面先来看一下例子:import j ...

最新文章

  1. Golang二维切片初始化
  2. ege函数库_EGE图形库|EGE图形库下载v12.11 最新版 附使用教程 - 欧普软件下载
  3. AI设计师“鹿班”核心技术公开:如何1秒设计8000张海报?
  4. lucene索引创建
  5. 2017.08.15【NOIP提高组】模拟赛B组 生日聚餐
  6. SCDPM 2012R2之保护SQL SERVER
  7. ads2020卸载 ads软件怎么卸载干净ads2016 ads2019卸载不干净无法重新安装 ads2017彻底卸载 ads2017卸载时删不尽
  8. python实现文件管理系统_Python - 文件管理系统
  9. win10 家庭版升级win11
  10. ffplay 加载 srt、ass字幕、调整对比度、亮度和饱和度、倍数播放
  11. linux查看服务器时间,Linux 查看当前时间
  12. 全民投资人游戏服务器维护,欢乐园《全民仙战》3月5日14时合服公告
  13. 线性回归模型度量参数2- Multiple R R-Squared adjusted R-squared
  14. Unity-URP学习笔记(八)使用RendererFeature制作屏幕后期-高斯模糊
  15. 从“棱镜门”事件看数据安全如何保护
  16. 微信聊天记录同步电脑
  17. python弹幕爬虫_Python爬虫弹幕采集的简单分析
  18. 加速度传感器的基本组成
  19. java实现第七届蓝桥杯平方末尾
  20. python __getattr__和__setattr__

热门文章

  1. 笔记2--认识O(logN)的排序--快速排序
  2. 埃森哲:数字化转型成功的企业,他们都做到了这5点
  3. 知识变现创业者必读——《知识变现实操手册》
  4. VSTO 系列(06)-自定义任务窗格
  5. 2017年8月22日 星期二
  6. 【Grafana】【八】可视化之Stat、Gauge和Bar Gauge
  7. android通讯录实例(一)
  8. 热插拔技术--以ADM1177为例说明
  9. java中String.split() 简单学习
  10. 计算机工程实践 课程大纲,《计算机专业》实习教学大纲.doc