基于Qt的简单文本编辑器

1.Qt概述

       Qt是一个跨平台的C++图形用户界面应用程序框架。它为应用程序开发者提供建立艺术级图形界面所需的所有功能。它是完全面向对象的,很容易扩展,并且允许真正的组件编程。

2.Qt发展史

1991年 Qt最早由奇趣科技开发

1996年 进入商业领域,它也是目前流行的Linux桌面环境KDE的基础

2008年 奇趣科技被诺基亚公司收购,Qt称为诺基亚旗下的编程语言

2012年 Qt又被Digia公司收购

2014年4月 跨平台的集成开发环境Qt Creator3.1.0发布,同年5月20日配发了Qt5.3正式版,至此Qt实现了对iOS、Android、WP等各平台的全面支持。

当前Qt最新版本为 5.5.0

  1. 3.创建一个简单的Qt项目

打开Qt Creator 界面选择 New Project或者选择菜单栏 【文件】-【新建文件或项目】菜单项

弹出New Project对话框,选择Qt Widgets Application,

选择【Choose】按钮,弹出如下对话框

设置项目名称和路径,按照向导进行下一步,

选择编译套件

向导会默认添加一个继承自CMainWindow的类,可以在此修改类的名字和基类。继续下一步

即可创建出一个Qt桌面程序。

4..pro文件

在使用Qt向导生成的应用程序.pro文件格式如下:

.pro就是工程文件(project),它是qmake(一个协助简化跨平台进行专案开发的构建过程的工具程式,Qt附带的工具之一)自动生成的用于生产makefile的配置文件。.pro文件的写法如下:

  1. 注释从“#”开始,到这一行结束。
  2. 模板变量告诉qmake为这个应用程序生成哪种makefile。下面是可供使用的选择:TEMPLATE = app
    1. app -建立一个应用程序的makefile。这是默认值,所以如果模板没有被指定,这个将被使用。
    2. lib - 建立一个库的makefile。
    3. vcapp - 建立一个应用程序的VisualStudio项目文件。
    4. vclib - 建立一个库的VisualStudio项目文件。
    5. subdirs -这是一个特殊的模板,它可以创建一个能够进入特定目录并且为一个项目文件生成makefile并且为它调用make的makefile。
  3. #指定生成的应用程序名: TARGET = QtDemo
  4. #工程中包含的头文件HEADERS += include/painter.h
  5. #工程中包含的.ui设计文件FORMS += forms/painter.ui
  6. #工程中包含的源文件SOURCES += sources/main.cpp sources/painter.cpp
  7. #工程中包含的资源文件RESOURCES += qrc/painter.qrc
  8. greaterThan(QT_MAJOR_VERSION, 4): QT += widgets这条语句的含义是,如果QT_MAJOR_VERSION大于4(也就是当前使用的Qt5及更高版本)需要增加widgets模块。如果项目仅需支持Qt5,也可以直接添加“QT += widgets”一句。不过为了保持代码兼容,最好还是按照QtCreator生成的语句编写。
  9. #配置信息CONFIG用来告诉qmake关于应用程序的配置信息。
  10. CONFIG += c++11//使用c++11的特性在这里使用“+=”,是因为我们添加我们的配置选项到任何一个已经存在中。这样做比使用“=”那样替换已经指定的所有选项更安全。

5.一个简单的Qt程序

  1. Qt头文件没有.h后缀
  2. Qt一个类对应一个头文件,类名就是头文件名
  3. QApplication应用程序类
    1. 管理图形用户界面应用程序的控制流和主要设置。
    2. 是Qt的整个后台管理的命脉它包含主事件循环,在其中来自窗口系统和其它资源的所有事件处理和调度。它也处理应用程序的初始化和结束,并且提供对话管理
    3. 对于任何一个使用Qt的图形用户界面应用程序,都正好存在一个QApplication 对象,而不论这个应用程序在同一时间内是不是有0、1、2或更多个窗口。
  4. a.exec()程序进入消息循环,等待对用户输入进行响应。这里main()把控制权转交给Qt,Qt完成事件处理工作,当应用程序退出的时候exec()的值就会返回。在exec()中,Qt接受并处理用户和系统的事件并且把它们传递给适当的窗口部件。

6.搭建文本编辑器

本文本编辑器实现更改字体格式,字体大小,字体颜色,字体加粗、斜体,设置下划线功能。提供打开系统文件,保存编辑内容到系统硬盘功能。显示系统时间在文本编辑器右下方,每一秒变化一次。

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QToolBar>
#include<QLabel>
#include<QFontComboBox>
#include<QPushButton>
#include<QToolButton>
#include<QTextEdit>
#include<QStatusBar>
#include<QDateTime>
#include<QTimer>
#include<QFont>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("无标题文档");
    createMenuBar();
    createCentral();
    createToolBar();
    createStatusBar();
}
void MainWindow::createMenuBar(){
    QMenuBar* menuBar=this->menuBar();
    QMenu* fileMenu=menuBar->addMenu("File(F)");
    QMenu* editMenu=menuBar->addMenu("Edit(E)");
    QMenu* formatMenu=menuBar->addMenu("Fromat(O)");
    QMenu* checkMenu=menuBar->addMenu("Check(V)");
    QMenu* helpMenu=menuBar->addMenu("Help(H)");
    saveAct=fileMenu->addAction(QIcon("://filesave.png"),"saveFile(L)");
    newAct=fileMenu->addAction(QIcon("://filenew.png"),"newFile(N)");
    saveasAct=fileMenu->addAction(QIcon("://filesave.png"),"saveasFile");
    openAct=fileMenu->addAction(QIcon("://fileopen.png"),"openFile(O)");
    fileMenu->addAction(QIcon("://fileprint.png"),"print(P)");
    fileMenu->addAction("exit(X)");
    undoAct=editMenu->addAction(QIcon("://editundo.png"),"undo");
    redoAct=editMenu->addAction(QIcon("://editredo.png"),"redo");
    editMenu->addAction(QIcon("://editpaste.png"),"paste(P)");
    pasteAct=editMenu->addAction(QIcon("://editcopy.png"),"copy");
    cutAct=editMenu->addAction(QIcon("://editcut.png"),"cut(T)");

    connect(saveAct,QAction::triggered,this,MainWindow::saveFile);
    //新建文件
    connect(newAct,QAction::triggered,[=](){
        if(QMessageBox::question(this,"提示","您是否需要保存当前文件")
                ==QMessageBox::Yes){
            //没有打开文件的情况下,直接调用保存的槽函数
            //已经打开文件的情况下,直接保存并关闭
            //清空当前页面
            //实例QFile
               QFile file("D:/Qt1.txt");
               //定义文件内容字符串
               QString content= "写入文件的内容";
               //判断文件是否存在
               if(file.exists())
               {
                   QMessageBox::warning(this,"创建文件","文件已经存在!");
               }else
               {
                   //存在打开,不存在创建
                   file.open(QIODevice::ReadWrite | QIODevice::Text);
                   //写入内容,这里需要转码,否则报错。
                   QByteArray str = content.toUtf8();
                   //写入QByteArray格式字符串
                   file.write(str);
                   //提示成功
                   QMessageBox::warning(this,"创建文件","文件创建成功!");
               }
               //关闭文件
               file.close();
      }
    });
    //打开文件
    connect(openAct,QAction::triggered,[=](){
        QString filepath=QFileDialog::getOpenFileName(this);
        QFile f(filepath);
        if(f.open(QIODevice::ReadWrite)){
            QTextStream t(&f);
            t.setCodec(QTextCodec::codecForName("UTF-8"));//文件转码,防止出现中文乱码问题
            text->setText(t.readAll());
            this->setWindowTitle(filepath);

        }else{
            QMessageBox::warning(this,"警告","文件打开失败");
        }
        f.close();
    });
}
void MainWindow::createToolBar(){
    //设置保存
    QToolBar* toolBar=this->addToolBar("toolBar");
    toolBar->addAction(saveAct);
    //打开
    QToolBar* toolBar1=this->addToolBar("toolBar1");
    toolBar->addAction(openAct);
    toolBar->addSeparator();//设置分隔
    //另存为
    QToolBar* toolBar2=this->addToolBar("toolBar2");
    toolBar->addAction(saveasAct);
    //剪切
    QToolBar* toolBar3=this->addToolBar("toolBar3");
    toolBar->addAction(cutAct);
    //粘贴
    QToolBar* toolBar4=this->addToolBar("toolBar4");
    toolBar->addAction(pasteAct);
    toolBar->addSeparator();//设置分隔
    //撤回
    QToolBar* toolBar5=this->addToolBar("toolBar5");
    toolBar->addAction(undoAct);
    QToolBar* toolBar6=this->addToolBar("toolBar6");
    toolBar->addAction(redoAct);
    toolBar->addSeparator();//设置分隔
    //设置字体
    QLabel *fontType=new QLabel("字体",this);
    toolBar->addWidget(fontType);//把Label控件添加到菜单栏里
    QFontComboBox* fontCom=new QFontComboBox();
    toolBar->addWidget(fontCom);
    //设置绑定字体下拉框
    connect(fontCom,QFontComboBox::currentFontChanged,this,MainWindow::changeFontType);
    //设置字号图标
    QLabel *fontSize=new QLabel("  字号",this);
    toolBar->addWidget(fontSize);//把Label控件添加到菜单栏里
    QComboBox* fontSizeCom=new QComboBox();
    toolBar->addWidget(fontSizeCom);
    //设置字号大小
    connect(fontSizeCom,QComboBox::currentTextChanged,this,[=](QString size){
        QTextCharFormat format;
        format.setFontPointSize(size.toDouble());
        text->mergeCurrentCharFormat(format);
    });
    //用循环来表示字号的所有大小
    int i=10;
    while(i<=20){
        fontSizeCom->addItem(QString::number(i));//QString里的number方法可以把int类型转换为QString类型
        i++;
    }
    //设置加粗标识
    QToolButton* b=new QToolButton();
    b->setIcon(QIcon("://textbold.png"));
    toolBar->addWidget(b);

    b->setCheckable(true);
    //设置加粗功能
    connect(b,QToolButton::clicked,this,[=](){
        QTextCharFormat format1;
        format1.setFontWeight(text->fontWeight()==QFont::Bold?QFont::Normal:QFont::Bold);
        text->mergeCurrentCharFormat(format1);
    });
    //设置斜体
    QToolButton* b1=new QToolButton();
    b1->setIcon(QIcon("://textitalic.png"));
    toolBar->addWidget(b1);

    b1->setCheckable(true);
    connect(b1,QToolButton::clicked,this,[=](){
        QTextCharFormat format3;
        format3.setFontItalic(text->fontItalic()==false?true:false);
        //format3.setFontItalic(this);
       // format3.setFontItalic(this);
        text->mergeCurrentCharFormat(format3);
    });
    //设置下划线
    QToolButton* b2=new QToolButton();
    b2->setIcon(QIcon("://textunder.png"));
    toolBar->addWidget(b2);
    toolBar->addSeparator();//设置分隔
    b2->setCheckable(true);
    connect(b2,QToolButton::clicked,this,[=](){
         QTextCharFormat format;
         format.setFontUnderline(text->fontUnderline()==false?true:false);
         text->mergeCurrentCharFormat(format);
    });
    //字体颜色
    QToolButton* b3=new QToolButton();
    b3->setIcon(QIcon("://true-color.png"));
    toolBar->addWidget(b3);
    //改变颜色
    connect(b3,QToolButton::clicked,this,[=](){
        //对话框QDialog
        QColor color=QColorDialog::getColor();
       //更改文本颜色
       //模态
        QTextCharFormat format2;
        format2.setForeground(QBrush(color));
        text->mergeCurrentCharFormat(format2);
       //非模态
    });
}
void MainWindow::createCentral(){
    text=new QTextEdit();
    this->setCentralWidget(text);
}
void MainWindow::createStatusBar(){
    //页脚显示时间
    QStatusBar *statusBar=this->statusBar();
    time=new QLabel("  时间:",this);
    time->setText("时间:"+QDateTime::currentDateTime().toString());
    statusBar->addWidget(time);
    //动态显示时间在页脚
    QTimer *timer=new QTimer();
    timer->start(1000); // 每次发射timeout信号时间间隔为1秒
    connect(timer,QTimer::timeout,this,MainWindow::timerRes);
}
void MainWindow::changeFontType(QFont font){
    //改变字体款式
    QTextCharFormat format;
    format.setFontFamily(font.toString());
    text->mergeCurrentCharFormat(format);
}

void MainWindow::timerRes()
    {
       time->setText("时间:"+QDateTime::currentDateTime().toString());
    }
//文件保存
void MainWindow::saveFile(){
    QString filePath=QFileDialog::getSaveFileName(this);//得到文件保存路径
    save(filePath);
}
//封装一下保存文件的方法
void MainWindow::save(QString filePath){
    QString data=text->toPlainText();//toplaintext为纯文本
    QFile f(filePath);
    if(f.open(QIODevice::ReadWrite)){
        QTextStream t(&f);
        t<<data;
        this->setWindowTitle(filePath);
    }else{
        QMessageBox::warning(this,"警告","文件保存失败");//MessageBox为消息对话框
    }
    f.close();
}

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

main.cpp

#include "mainwindow.h"
#include <QApplication>

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

    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QLabel>
#include<QTextEdit>
#include<QFont>
#include<QColorDialog>
#include<QFileDialog>
#include<QTextStream>
#include<QMessageBox>
#include<QTextCodec>
#include <QDir>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void timerRes();
    void createMenuBar();
    void createToolBar();
    void createStatusBar();
    void createCentral();
    void changeFontType(QFont font);
    void saveFile();
    void save(QString filePath);
    QAction* saveAct;
    QAction* newAct;
    QAction* openAct;
    QAction* saveasAct;
    QAction* undoAct;
    QAction* redoAct;
    QAction* pasteAct;
    QAction* cutAct;
    QLabel *time;
    QTextEdit *text;
private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

用到的资源文件URL:https://download.csdn.net/download/m0_47539378/20069636?spm=1001.2014.3001.5503

资源文件影响不大,只是贴图而已。可下载可不下载。

  • 7
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个基于Qt5中widgets框架编写的简易多文档编辑器的示例: ```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog class TextEditor(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) self.createActions() self.createMenus() self.setWindowTitle("Text Editor") self.setGeometry(100, 100, 800, 600) self.show() def createActions(self): self.newAct = QAction("New", self) self.newAct.setShortcut("Ctrl+N") self.newAct.triggered.connect(self.newFile) self.openAct = QAction("Open", self) self.openAct.setShortcut("Ctrl+O") self.openAct.triggered.connect(self.openFile) self.saveAct = QAction("Save", self) self.saveAct.setShortcut("Ctrl+S") self.saveAct.triggered.connect(self.saveFile) def createMenus(self): self.fileMenu = self.menuBar().addMenu("File") self.fileMenu.addAction(self.newAct) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.saveAct) def newFile(self): self.textEdit.clear() def openFile(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open File") if fileName: with open(fileName, "r") as file: self.textEdit.setText(file.read()) def saveFile(self): fileName, _ = QFileDialog.getSaveFileName(self, "Save File") if fileName: with open(fileName, "w") as file: file.write(self.textEdit.toPlainText()) if __name__ == "__main__": app = QApplication(sys.argv) editor = TextEditor() sys.exit(app.exec_()) ``` 这个多文档文本编辑器具有新建、打开、保存文件的功能。你可以使用菜单栏中的"File"选项来执行这些操作。此外,你还可以在文本编辑器中设置字体、字号、文字的复制、粘贴、加粗、倾斜以及设置字体颜色等功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

.Diamond.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值