功能基本完善的记事本(可实现查找功能且附带详细代码和教程)

功能基本完善的记事本(可实现查找功能且附带详细代码和教程)

前言

学习Qt已经 好长时间了,在通过几个模块化的学习后,想要写一些东西,学了基本控件,信号和槽,对话框,文件与目录的输入输出等。感受能够作一个简单的记事本。其实昨天上传过一次,查找和替换写的很差,由于实战经验少,一直不知道该如何对那么多控件布局,睡觉的时候忽然惊醒能够直接再写对话框窗口呀!!!瞬间清醒过来,又写了一下。基本的复制粘贴和剪切功能我的感受QTextedit控件自带的有,就没有写…web

功能

1.文件(新建,打开,保存,另存为,打印,退出)
2.字体格式(字体大小,颜色,形式,加粗,倾斜,下划线)
3.文本格式(对齐方式)
4.编辑功能(复制,粘贴,删除,全选,查找,替换)windows

废话很少说直接上代码:
mainwindow.cppide

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    isunderline=false;
    isItalic=false;
    isheight=false;
    pad = new QTextEdit;
    this->setCentralWidget(pad);
    resize(900,500);
    pad->setText("");


    createActions();//菜单栏行为
    createMenus();//文件菜单栏函数
    createToolbar();//工具栏


    void (finddialog::*findsignals)(QString) = &finddialog::findText;
    connect(&fdg,findsignals,this,&MainWindow::dealfromfind);


    void (replace::*replacesignals)(QString,QString) = &replace::replaceText;
    connect(&rdg,replacesignals,this,&MainWindow::dealfromreplace);
}


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


//-----------------建立菜单栏函数-------------
void MainWindow::createMenus(){


    //————文件————
    file_menu = menuBar()->addMenu(tr("&文件"));
    file_menu->setStyleSheet("color:blue");
    file_menu->addAction(new_file);
    file_menu->addAction(open_file);
    file_menu->addAction(save_file);
    file_menu->addAction(another_save_file);
    file_menu->addAction(print_file);
    file_menu->addSeparator();//添加分割线
    file_menu->addAction(exit_file);


    //———编辑———
    edit_menu = menuBar()->addMenu(tr("&编辑"));
    edit_menu->setStyleSheet("color:blue");
    edit_menu->addAction(edit_font);
    edit_menu->addAction(edit_Wedight);
    edit_menu->addAction(edit_Italic);
    edit_menu->addAction(edit_Underline);
    edit_menu->addAction(edit_AlignLeft);
    edit_menu->addAction(edit_AlignRigeht);
    edit_menu->addAction(edit_AlignCenter);
    edit_menu->addAction(edit_color);
    edit_menu->addAction(edit_find);
    edit_menu->addAction(edit_replace);


    //———关于————
    about_menu = menuBar()->addMenu(tr("关于"));
    about_menu->setStyleSheet("color:blue");
    about_menu->addAction(about_help);
    about_menu->addAction(about_fabricator);


}


void MainWindow::createActions(){
    //Action响应file_menu
    new_file = new QAction(QIcon(tr(":/new/prefix1/images/xinjian.png")),tr("&新建"),this);
    new_file->setShortcut(QKeySequence::New);


    open_file= new QAction(QIcon(tr(":/new/prefix1/images/dakaiwenjian.png")),tr("&打开"),this);
    open_file->setShortcut(QKeySequence::Open);


    save_file = new QAction(QIcon(tr(":/new/prefix1/images/baocun.png")),tr("&保存"),this);
    save_file->setShortcut(QKeySequence::Save);


    another_save_file = new QAction(QIcon(tr(":/new/prefix1/images/lingcunwei")),tr("&另存为"),this);
    another_save_file->setShortcut(QKeySequence::SaveAs);


    print_file= new QAction(QIcon(tr(":/new/prefix1/images/dayin.png")),tr("&打印"),this);
    print_file->setShortcut(QKeySequence::Print);


    exit_file = new QAction(QIcon(tr(":/new/prefix1/images/tuichu")),tr("&退出"),this);
    exit_file->setShortcut(QKeySequence::Quit);


    //——————编辑————————
    edit_font = new QAction(QIcon(tr(":/new/prefix1/images/zitifont5.png")),tr("&字体"),this);


    edit_color = new QAction(QIcon(tr(":/new/prefix1/images/yanse.png")),tr("&颜色"),this);


    edit_Wedight = new QAction(QIcon(tr(":/new/prefix1/images/jiacu.png")),tr("&加粗"),this);


    edit_Italic = new QAction(QIcon(tr(":/new/prefix1/images/qingxie.png")),tr("&倾斜"),this);


    edit_Underline =  new QAction(QIcon(tr(":/new/prefix1/images/Underline.png")),tr("&下划线"),this);


    edit_AlignLeft = new QAction(QIcon(tr(":/new/prefix1/images/zuoduiqi")),tr("&左对齐"),this);


    edit_AlignRigeht = new QAction(QIcon(tr(":/new/prefix1/images/youduiqi")),tr("&右对齐"),this);


    edit_AlignCenter = new QAction(QIcon(tr(":/new/prefix1/images/juzhong")),tr("&居中"),this);


    edit_find = new QAction(QIcon(tr(":/images/tuichu")),tr("&查找"),this);


    edit_replace = new QAction(QIcon(tr(":/images/tuichu")),tr("&替换"),this);






  // edit_Wedight = new QAction();


    //————————关于————————
    about_help = new QAction(QIcon(tr("../images/tuichu")),tr("&帮助"),this);
    about_fabricator = new QAction(QIcon(tr("../images/tuichu")),tr("&制做人"),this);




    //信号和槽


    //————————文件——————
    connect(new_file,SIGNAL(triggered()),this,SLOT(newFile()));


    connect(open_file,SIGNAL(triggered()),this,SLOT(openFile()));


    connect(save_file,SIGNAL(triggered()),this,SLOT(saveFile()));


    connect(another_save_file,SIGNAL(triggered()),this,SLOT(anotherSaveFile()));


    connect(print_file,SIGNAL(triggered()),this,SLOT(printFile()));


    connect(exit_file,SIGNAL(triggered()),this,SLOT(QuitFile()));


    //————编辑————————
    connect(edit_font,SIGNAL(triggered()),this,SLOT(editFont()));


    connect(edit_Wedight,SIGNAL(triggered()),this,SLOT(editWedight()));


    connect(edit_Italic,SIGNAL(triggered()),this,SLOT(editItalic()));


    connect(edit_Underline,SIGNAL(triggered()),this,SLOT(editUnderline()));


     connect(edit_AlignLeft,SIGNAL(triggered()),this,SLOT(AlignLeft()));


    connect(edit_AlignRigeht,SIGNAL(triggered()),this,SLOT(AlignRight()));


    connect(edit_AlignCenter,SIGNAL(triggered()),this,SLOT(AlignCenter()));


    connect(edit_color,SIGNAL(triggered()),this,SLOT(editColor()));


    connect(edit_find,SIGNAL(triggered()),this,SLOT(editFind()));
    connect(edit_replace,SIGNAL(triggered()),this,SLOT(editReplace()));


    //——————关于——————
    connect(about_help,SIGNAL(triggered()),this,SLOT(abouthelp()));


    connect(about_fabricator,SIGNAL(triggered()),this,SLOT(aboutfabricator()));


}


void MainWindow::createToolbar(){
    QToolBar *tool_bar = addToolBar(tr("file"));
    tool_bar->addAction(new_file);//
    tool_bar->addAction(open_file);//
    tool_bar->addAction(save_file);//
    tool_bar->addAction(another_save_file);//
    tool_bar->addAction(print_file);//
    tool_bar->addAction(edit_Wedight);//
    tool_bar->addAction(edit_Italic);//
    tool_bar->addAction(edit_Underline);//
    tool_bar->addAction(edit_font);//
    tool_bar->addAction(edit_color);//
    tool_bar->addAction(edit_AlignLeft);//
    tool_bar->addAction(edit_AlignRigeht);//
    tool_bar->addAction(edit_AlignCenter);//


    tool_bar->addAction(exit_file);//


}


void MainWindow::newFile(){
    if (pad->document()->isModified())
    {
        QMessageBox::StandardButton button = QMessageBox::information(this,
                                          "还没有保存", "是否要保存?",QMessageBox::Save |
                                           QMessageBox::Discard | QMessageBox::Cancel);
        switch(button)
        {
            case QMessageBox::Save:{
                saveFile();
                if (pad->document()->isModified()){
                    return;
                }
            }
            case QMessageBox::Cancel:{
                return;
            }
            case QMessageBox::Discard:{
                break;
            }
        }
    }
    pad->clear();
}


void MainWindow::openFile(){
    QString filename = QFileDialog::getOpenFileName(this,tr("文件对话框"),
                                "D:",tr("文本文档(*txt *word *rtf)"));


    str=filename;
    if(!filename.isEmpty()){
       QFile file(filename);
       if(!file.open(QIODevice::ReadOnly)){
          QMessageBox::critical(this,tr("错误"),tr("不能打开文件"));
          return;
       }
       QTextStream streamcin(&file);
       streamcin.setCodec("UTF-8");
       pad->setText(streamcin.readAll());
       file.close();
    }
}


void MainWindow::saveFile(){


    if(str.isEmpty()){
        QString filename = QFileDialog::getSaveFileName(this,tr("保存文件"),QString(),
                               tr("文本文件(*.txt) ;; C++文件(*.h *.cpp *.hpp)"));
        if(!filename.isEmpty()){
            QFile file(filename);
            if(!file.open(QIODevice::WriteOnly)){
                QMessageBox::critical(this,tr("错误"),tr("不能打开文件"));
                return;
            }
            QTextStream streamout(&file);
            streamout.setCodec("UTF-8");
            streamout<<pad->toPlainText();
            streamout.flush();
            file.close();
        }
    }
    else{
        QFile file(str);
        if(!file.open(QIODevice::WriteOnly)){
            QMessageBox::critical(this,tr("错误"),tr("不能打开文件"));
            return;
        }
        QTextStream streamout(&file);
        streamout.setCodec("UTF-8");
        streamout<<pad->toPlainText();
        streamout.flush();
        file.close();
    }
}


void MainWindow::anotherSaveFile()
{
    QString filename = QFileDialog::getSaveFileName(this,tr("保存文件"),QString(),
                           tr("文本文件(*.txt) ;; C++文件(*.h *.cpp *.hpp)"));
    if(!filename.isEmpty()){
        QFile file(filename);
        if(!file.open(QIODevice::WriteOnly)){
            QMessageBox::critical(this,tr("错误"),tr("不能打开文件"));
            return;
        }
        QTextStream streamout(&file);
        streamout.setCodec("UTF-8");
        streamout<<pad->toPlainText();
        streamout.flush();
        file.close();
    }
}


void MainWindow::printFile(){
    QMessageBox::information(this,"通知","本功能暂时没法使用");
    QPrinter q;
       //打印对话框.
    QPrintDialog s(&q, this);
    if (s.exec() == QDialog::Accepted)
           pad->print(&q);
}


void MainWindow::QuitFile(){
    this->close();
}


void MainWindow::editFont(){
    bool ok;
        QFont font=QFontDialog::getFont(&ok,this);
        if(ok){
            pad->setFont(font);
        }
        else{
           QMessageBox::warning(this,tr("警告"),tr("没有选择字体"),QMessageBox::Yes);
        }
}


void MainWindow::editColor(){


    QColor color = QColorDialog::getColor(Qt::red,this,tr("颜色对话框"));


    pad->setTextColor(color);


}


void MainWindow::editWedight(){//加粗


    QFont boldFont;
    if(isheight==false){
    boldFont.setBold(true);
    isheight=true;
    }
    else
    {
        boldFont.setBold(false);
        isheight=false;
    }
    pad->setFont(boldFont);
}


void MainWindow::editItalic(){//倾斜
    if(isItalic==false){
        pad->setFontItalic(true);
        isItalic=true;
    }
    else{
        pad->setFontItalic(false);
        isItalic=false;
    }


}


void MainWindow::editUnderline(){//下划线
    if(isunderline==false){
        pad->setFontUnderline(true);
        isunderline=true;
    }
    else{
        pad->setFontUnderline(false);
        isunderline=false;
    }
}


void MainWindow::AlignLeft(){//对齐方式左对齐
    pad->setAlignment(Qt::AlignLeft);
}


void MainWindow::AlignRight(){//对齐方式右对齐
    pad->setAlignment(Qt::AlignRight);
}


void MainWindow::AlignCenter(){//对齐方式居中对齐
    pad->setAlignment(Qt::AlignCenter);
}


void MainWindow::editFind(){//查找按钮点后出来查找对话框
    fdg.show();
}


void MainWindow::dealfromfind(QString str){//收到查找对话框传来的信息开始查找


    if (str.trimmed().isEmpty()) {
            QMessageBox::information(this, tr("警告"), tr("输入框为空"));
     }
    else
    {
        if(pad->find(str,QTextDocument::FindBackward))
        {
            QPalette palette = pad->palette();
            palette.setColor(QPalette::Highlight,palette.color(QPalette::Active,QPalette::Highlight));
            pad->setPalette(palette);
        }
        else{
            QMessageBox::information(this,tr("查找"),tr("没有找到该字符串"));
        }
    }
}


void MainWindow::editReplace(){
    rdg.show();
}


void MainWindow::dealfromreplace(QString findstr,QString replacestr){


    if (findstr.trimmed().isEmpty()) {
            QMessageBox::information(this, tr("警告"), tr("输入框为空"));
     }


    else{
        if(pad->find(findstr,QTextDocument::FindBackward)){
             QTextCursor cursor = pad->textCursor();
            cursor.insertText(replacestr);


        }
        else{
                   QMessageBox::information(this,tr("结果"),tr("没有内容不能替换:")+str,QMessageBox::Yes);
                   rdg.hide();
        }
    }
}


QWizardPage * MainWindow::createPage1()
{
    QWizardPage * page = new QWizardPage;
    page->setTitle(tr("介绍:\n参照windows自带的记事本,能够实现文件的新建保存打印以及格式的修改\n"
                      "制做人:王啸楠"));
    return page;
}


QWizardPage * MainWindow::createPage2()
{
    QWizardPage * page = new QWizardPage;
    page->setTitle("使用方式1:加粗,倾斜,下划线等功能点击后为相反样式\n如:未加粗文字点后会加粗,加粗文字点击后会变为未加粗");
    return page;
}


QWizardPage * MainWindow::createPage3()
{
    QWizardPage * page = new QWizardPage;
    page->setTitle("使用方式2:对于查找和替换功能请保证光标在末尾处(实现的是倒叙查找和替换)");
    return page;
}


QWizardPage * MainWindow::createPage4()
{
    QWizardPage * page = new QWizardPage;
    page->setTitle("结束");
    return page;
}


void MainWindow::abouthelp(){
    int ret = QMessageBox::question(this,tr("帮助文档"),
                                         tr("请参照wps,若没有用过wps请点击no"),QMessageBox::Yes,QMessageBox::No);
    if(ret==QMessageBox::No){
        QWizard wizard(this);
           wizard.setWindowTitle("帮助文档");
           wizard.addPage(createPage1());
           wizard.addPage(createPage2());
           wizard.addPage(createPage3());
           wizard.addPage(createPage4());
           wizard.exec();
    }


}


void MainWindow::aboutfabricator(){
    QMessageBox::information(this,tr("制做人"),tr("王啸楠"));
}

finddialog.cppsvg

#include "finddialog.h"


finddialog::finddialog(QWidget *parent) : QDialog(parent)
{
    this->setWindowTitle("查找");


    resize(300,120);
    creatpbt();
}


finddialog::~finddialog(){


}


void finddialog::creatpbt(){


    a = new QLabel(this);
    a->move(25,20);
    a->setText("请输入要查找的字符串:");


    lineedit = new QLineEdit(this);
    lineedit->move(25,40);


    find_pbt = new QPushButton(tr("查找(下一个)"),this);


    find_pbt->move(180,10);


    cancel_pbt = new QPushButton(tr("取消"),this);


    cancel_pbt->move(180,70);
    connect(find_pbt,&QPushButton::clicked,this,&finddialog::findpdt);
    connect(cancel_pbt,&QPushButton::clicked,this,&QDialog::close);
}


void finddialog::findpdt(){
        findtext = lineedit->text();
        //发出信号.
        emit findText(findtext);
}

replace.cpp模块化

#include "replace.h"


replace::replace(QWidget *parent) : QDialog(parent)
{
    this->setWindowTitle("替换");


    resize(300,120);
    creatpbt();
}


replace::~replace(){


}


void replace::creatpbt(){


      a = new QLabel(this);
      a->move(25,15);
      a->setText("请输入被替换的字符串:");


      findedit = new QLineEdit(this);
      findedit->move(25,30);




      b = new QLabel(this);
      b->move(25,60);
      b->setText("请输入替换的字符串:");
      replaceedit = new QLineEdit(this);
      replaceedit->move(25,75);


      replace_pbt = new QPushButton(tr("替换"),this);
      replace_pbt->move(180,10);


      cancel_pbt = new QPushButton(tr("取消"),this);
      cancel_pbt->move(180,70);


      connect(replace_pbt,&QPushButton::clicked,this,&replace::replacepdt);
      connect(cancel_pbt,&QPushButton::clicked,this,&replace::close);


}


void replace::replacepdt(){


    QString str1,str2;
    str1=findedit->text();
    str2=replaceedit->text();


    emit replaceText(str1,str2);
}

由于这个文件还要审核后才能发出暂时没有下载连接…
你们能够私聊我。函数