首页 > 代码库 > 第三十五课、文本编辑器中的数据存取

第三十五课、文本编辑器中的数据存取

一、QAction的信号

1、QAction被点击之后会产生一个triggered信号

(1)、通过信号与槽的机制能够捕捉对QAction对象的操作

(2)、项目中可以将多个信号映射到同一个槽函数

技术分享

二、文件的打开、保存、另存为操作

1、文件的打开操作

技术分享

2、文件的保存操作

(1)、定义成员变量用于标记数据来源

技术分享

3、文件的另存为操作

技术分享

技术分享
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QString>
#include <QtGui/QMainWindow>
#include <QToolBar>
#include <QIcon>
#include <QSize>
#include <QStatusBar>
#include <QLabel>
#include <QPlainTextEdit>
#include <QFileDialog>
class MainWindow : public QMainWindow
{
    Q_OBJECT
private:
        QPlainTextEdit mainEdit;
        QLabel statusLabel;
        QString m_filePath;//记得在构造函数里初始化

        MainWindow(QWidget *parent = 0);
        MainWindow(const MainWindow& obj);
        MainWindow* operator = (const MainWindow& obj);
        bool construct();

        bool initMenuBar();//菜单栏
        bool initToolBar();//工具栏
        bool initStatusBar();//状态栏
        bool initinitMainEditor();//编辑窗口

        bool initFileMenu(QMenuBar* mb);//文件菜单
        bool initEditMenu(QMenuBar* mb);//编辑菜单
        bool initFormatMenu(QMenuBar* mb);//格式菜单
        bool initViewMenu(QMenuBar* mb);//视图菜单
        bool initHelpMenu(QMenuBar* mb);//帮助菜单

        bool initFileToolItem(QToolBar* tb);//工具选项
        bool initEditToolItem(QToolBar* tb);
        bool initFormatToolItem(QToolBar* tb);
        bool initViewToolItem(QToolBar* tb);


        bool makeAction(QAction*& action,QMenu* menu, QString text, int key);//菜单项
        bool makeAction(QAction*& action,QToolBar* tb, QString tip, QString icon);

        QString showFileDialog(QFileDialog::AcceptMode mode, QString title);//文件对话框
        void showErrorMessage(QString message);//错误消息对话框

private slots:
        void onFileOpen();
        void onFlieSave();
        void onFileSaveAs();
public:
     static MainWindow* NewInstance();
    ~MainWindow();
};

#endif // MAINWINDOW_H
MainWindow.h
技术分享
#include "MainWindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), statusLabel(this)
{
    m_filePath = "";
}

bool MainWindow::construct()
{
    bool ret = true;
    ret = ret && initMenuBar();
    ret = ret && initToolBar();
    ret = ret && initStatusBar();
    ret = ret && initinitMainEditor();
    return ret;
}
MainWindow* MainWindow::NewInstance()
{
    MainWindow* ret = new MainWindow();

    if((ret==NULL) || (!ret->construct()))
    {
        delete ret;
        ret = NULL;
    }

    return ret;
}
bool MainWindow::initMenuBar()//菜单栏
{
    bool ret = true;

    QMenuBar* mb = menuBar();//一定要注意是menuBar(),这是普通成员函数,不是构造函数

    ret = ret && initFileMenu(mb);//传一个参数是为了在initFileMenu()函数将menu加入菜单栏
    ret = ret && initEditMenu(mb);
    ret = ret && initFormatMenu(mb);
    ret = ret && initViewMenu(mb);
    ret = ret && initHelpMenu(mb);

    return ret;

}

bool MainWindow::initToolBar()//工具栏
{
    bool ret = true;

    QToolBar* tb = addToolBar("Tool Bar");
    //tb->setMovable(false);
    //tb->setFloatable(false);
    tb->setIconSize(QSize(16,16));

    ret = ret && initFileToolItem(tb);
    tb->addSeparator();
    ret = ret && initEditToolItem(tb);
    tb->addSeparator();
    ret = ret && initFormatToolItem(tb);
    tb->addSeparator();
    ret = ret && initViewToolItem(tb);

    return ret;
}

bool MainWindow::initStatusBar()//状态栏
{
    bool ret = true;

    QStatusBar* sb = statusBar();

    QLabel* label = new QLabel("Made By LGC");

    if(label != NULL)
    {
        statusLabel.setMinimumWidth(200);
        statusLabel.setAlignment(Qt::AlignHCenter);
        statusLabel.setText("Ln:1    Col:1");


        label->setMinimumWidth(200);
        label->setAlignment(Qt::AlignHCenter);

        sb->addPermanentWidget(new QLabel());//单纯加入分隔符
        sb->addPermanentWidget(&statusLabel);
        sb->addPermanentWidget(label);
    }
    else
    {
        ret = false;
    }
    return ret;
}
bool MainWindow::initinitMainEditor()//编辑窗口
{
    bool ret = true;

    mainEdit.setParent(this);
    setCentralWidget(&mainEdit);

    return ret;
}

/************************************************文件菜单********************************************************/
bool MainWindow::initFileMenu(QMenuBar* mb)
{
    bool ret = true;

    QMenu* menu = new QMenu("File(&F)");//创建文件菜单,(&F)是为了可以Alt+F打开
    ret = (menu != NULL);
    if(ret)
    {
        QAction* action = NULL;

        //New
        ret = ret &&  makeAction(action, menu, "New(&N)",Qt::CTRL + Qt::Key_N);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Open
        ret = ret &&  makeAction(action,  menu,"Open(&O)...",Qt::CTRL + Qt::Key_O);
        if(ret)
        {
           connect(action, SIGNAL(triggered()), this, SLOT(onFileOpen()));
           menu->addAction(action);
        }

        menu->addSeparator();

        //Save
        ret = ret &&  makeAction(action,  menu,"Save(&S)",Qt::CTRL + Qt::Key_S);
        if(ret)
        {
            connect(action, SIGNAL(triggered()), this ,SLOT(onFlieSave()));
            menu->addAction(action);
        }

        menu->addSeparator();

        //Save As
        ret = ret &&  makeAction(action, menu, "Save As(&A)...",0);
        if(ret)
        {
           connect(action, SIGNAL(triggered()), this, SLOT(onFileSaveAs()));
           menu->addAction(action);

        }

        menu->addSeparator();

        //print
        ret = ret &&  makeAction(action, menu, "Print(&P)...",Qt::CTRL + Qt::Key_P);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Exit
        ret = ret &&  makeAction(action,  menu,"Exit(&X)",0);
        if(ret)
        {
           menu->addAction(action);//将菜单项加入到菜单
        }

    }
    if(ret)
    {
        mb->addMenu(menu);//将菜单加入到菜单栏
    }
    else
    {
        delete mb;
    }
    return ret;
}

/************************************************编辑菜单********************************************************/
bool MainWindow::initEditMenu(QMenuBar* mb)
{
    bool ret = true;

    QMenu* menu = new QMenu("Edit(&E)");
    ret = (menu != NULL);
    if(ret)
    {
        QAction* action = NULL;

        //Undo
        ret = ret &&  makeAction(action,  menu,"Undo(&U)",Qt::CTRL + Qt::Key_Z);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Redo
        ret = ret &&  makeAction(action,  menu,"Redo(&R)...",Qt::CTRL + Qt::Key_Y);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Cut
        ret = ret &&  makeAction(action,  menu,"Cut(&T)",Qt::CTRL + Qt::Key_X);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Copy
        ret = ret &&  makeAction(action,  menu,"Copy(&C)...",Qt::CTRL + Qt::Key_C);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Pase
        ret = ret &&  makeAction(action,  menu,"Pase(&P)...",Qt::CTRL + Qt::Key_V);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Delete
        ret = ret &&  makeAction(action, menu, "Delete(&L)",Qt::Key_Delete);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Find
        ret = ret &&  makeAction(action,  menu,"Find(&F)...",Qt::CTRL + Qt::Key_F);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Replace
        ret = ret &&  makeAction(action,  menu,"Replace(&R)...",Qt::CTRL + Qt::Key_H);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Goto
        ret = ret &&  makeAction(action,  menu,"Goto(&G)",Qt::CTRL + Qt::Key_G);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Select All
        ret = ret &&  makeAction(action, menu, "Select All(&A)",Qt::CTRL + Qt::Key_A);
        if(ret)
        {
           menu->addAction(action);
        }

    }
    if(ret)
    {
        mb->addMenu(menu);
    }
    else
    {
        delete mb;
    }
    return ret;
}

/************************************************格式菜单********************************************************/
bool MainWindow::initFormatMenu(QMenuBar* mb)
{
    bool ret = true;

    QMenu* menu = new QMenu("Format(&O)");
    ret = (menu != NULL);
    if(ret)
    {
        QAction* action = NULL;

        //Auto Wrap
        ret = ret &&  makeAction(action,  menu,"Auto Wrap(&W)",0);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Font
        ret = ret &&  makeAction(action,  menu,"Font(&F)...",0);
        if(ret)
        {
           menu->addAction(action);
        }

    }
    if(ret)
    {
        mb->addMenu(menu);
    }
    else
    {
        delete mb;
    }
    return ret;
}

/************************************************视图菜单********************************************************/
bool MainWindow::initViewMenu(QMenuBar* mb)
{
    bool ret = true;

    QMenu* menu = new QMenu("View(&V)");
    ret = (menu != NULL);
    if(ret)
    {
        QAction* action = NULL;

        //Tool Bar
        ret = ret &&  makeAction(action, menu,"Tool Bar(&T)",0);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //Status Bar
        ret = ret &&  makeAction(action, menu,"Status Bar(&S)",0);
        if(ret)
        {
           menu->addAction(action);
        }

    }
    if(ret)
    {
        mb->addMenu(menu);
    }
    else
    {
        delete mb;
    }
    return ret;
}

/************************************************帮助菜单********************************************************/
bool MainWindow::initHelpMenu(QMenuBar* mb)
{
    bool ret = true;

    QMenu* menu = new QMenu("Help(&H)");
    ret = (menu != NULL);
    if(ret)
    {
        QAction* action = NULL;

        //User Manual
        ret = ret &&  makeAction(action,  menu,"User Manual",0);
        if(ret)
        {
           menu->addAction(action);
        }

        menu->addSeparator();

        //About NotePad
        ret = ret &&  makeAction(action,  menu,"About NotePad...",0);
        if(ret)
        {
           menu->addAction(action);
        }

    }
    if(ret)
    {
        mb->addMenu(menu);
    }
    else
    {
        delete mb;
    }
    return ret;
}
/*****************************************工具************************************************************/
bool MainWindow::initFileToolItem(QToolBar* tb)
{
    bool ret = true;
    QAction* action = NULL;

    ret = ret && makeAction(action, tb, "New", ":/Res/pic/new.png");
    if(ret)
    {
        tb->addAction(action);

    }

    ret = ret && makeAction(action,  tb,"Open", ":/Res/pic/open.png");
    if(ret)
    {
        connect(action, SIGNAL(triggered()), this, SLOT(onFileOpen()));
        tb->addAction(action);
    }

    ret = ret && makeAction(action,  tb,"Save", ":/Res/pic/save.png");
    if(ret)
    {
        connect(action, SIGNAL(triggered()), this ,SLOT(onFlieSave()));
        tb->addAction(action);
    }

    ret = ret && makeAction(action,  tb,"Save As", ":/Res/pic/saveas.png");
    if(ret)
    {
        connect(action, SIGNAL(triggered()), this, SLOT(onFileSaveAs()));
        tb->addAction(action);
    }
    ret = ret && makeAction(action, tb,"Print",  ":/Res/pic/print.png");
    if(ret)
    {
        tb->addAction(action);
    }
    return ret;

}
bool MainWindow::initEditToolItem(QToolBar* tb)
{
    bool ret = true;
    QAction* action = NULL;

    ret = ret && makeAction(action, tb,"Undo",  ":/Res/pic/undo.png");
    if(ret)
    {
        tb->addAction(action);
    }
    ret = ret && makeAction(action,  tb,"Redo", ":/Res/pic/redo.png");
    if(ret)
    {
        tb->addAction(action);
    }

    ret = ret && makeAction(action, tb, "Cut",  ":/Res/pic/cut.png");
    if(ret)
    {
        tb->addAction(action);
    }

    ret = ret && makeAction(action,  tb,"Copy", ":/Res/pic/copy.png");
    if(ret)
    {
        tb->addAction(action);
    }

    ret = ret && makeAction(action, tb,"Paste",  ":/Res/pic/paste.png");
    if(ret)
    {
        tb->addAction(action);
    }

    ret = ret && makeAction(action, tb,"Find",  ":/Res/pic/find.png");
    if(ret)
    {
        tb->addAction(action);
    }
    ret = ret && makeAction(action, tb,"Replace",  ":/Res/pic/replace.png");
    if(ret)
    {
        tb->addAction(action);
    }
    ret = ret && makeAction(action, tb,"Goto",  ":/Res/pic/goto.png");
    if(ret)
    {
        tb->addAction(action);
    }

    return ret;
}
bool MainWindow::initFormatToolItem(QToolBar* tb)
{
    bool ret = true;
    QAction* action = NULL;

    ret = ret && makeAction(action, tb, "Auto Wrap", ":/Res/pic/wrap.png");
    if(ret)
    {
        tb->addAction(action);
    }
    ret = ret && makeAction(action, tb,"Font",  ":/Res/pic/font.png");
    if(ret)
    {
        tb->addAction(action);
    }

    return ret;
}
bool MainWindow::initViewToolItem(QToolBar* tb)
{
    bool ret = true;
    QAction* action = NULL;

    ret = ret && makeAction(action,  tb,"Tool Bar", ":/Res/pic/tool.png");
    if(ret)
    {
        tb->addAction(action);
    }
    ret = ret && makeAction(action,  tb,"Status Bar", ":/Res/pic/status.png");
    if(ret)
    {
        tb->addAction(action);
    }

    return ret;
}


bool MainWindow::makeAction(QAction*& action,QMenu* menu, QString text, int key)//菜单项
{
    bool ret = true;
    action = new QAction(text, menu);
    if(action != NULL)
    {
        action->setShortcut(QKeySequence(key));//创建快捷键
    }
    else
    {
        ret = false;
    }

    return ret;
}
bool MainWindow::makeAction(QAction*& action,QToolBar* tb, QString tip, QString icon)
{
    bool ret = true;
    action = new QAction("", tb);
    if(action != NULL)
    {
        action->setToolTip(tip);
        action->setIcon(QIcon(icon));
    }
    else
    {
        ret = false;
    }
    return ret;
}
MainWindow::~MainWindow()
{

}
MainWindowUI.cpp
技术分享
#include <QFileDialog>
#include <QStringList>
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include "MainWindow.h"

QString MainWindow::showFileDialog(QFileDialog::AcceptMode mode, QString title)
{
    QString ret = "";
    QFileDialog fd;

    fd.setWindowTitle(title);
    fd.setAcceptMode(mode);
    QStringList filters;
    filters.append("Text(*.txt)");
    filters.append("All Files(*.*)");
    fd.setNameFilters(filters);

    if(mode==QFileDialog::AcceptOpen)
    {
        fd.setFileMode(QFileDialog::ExistingFile);
    }

    if(fd.exec()==QFileDialog::Accepted)
    {
        ret = fd.selectedFiles()[0];
    }

    return ret;
}

void MainWindow::showErrorMessage(QString message)
{
    QMessageBox mb(this);

    mb.setWindowTitle("Error");
    mb.setText("message");
    mb.setIcon(QMessageBox::Critical);
    mb.setStandardButtons(QMessageBox::Ok);

    mb.exec();
}

void MainWindow::onFileOpen()
{
    QString path = showFileDialog(QFileDialog::AcceptOpen, "open");

    if(path != "")
    {
        QFile file(path);
        if(file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            mainEdit.setPlainText(QString(file.readAll()));

            file.close();

            m_filePath = path;//报存当前文件路径

            setWindowTitle("NotePad - [" + m_filePath + "]");
        }
        else
        {
            showErrorMessage(QString("Open file Error!\n\n") + "\"" + m_filePath + "\"");
        }
    }
}

void MainWindow::onFlieSave()
{
    if(m_filePath == "")
    {
        m_filePath = showFileDialog(QFileDialog::AcceptSave, "Save");

    }

    if(m_filePath != "")
    {
        QFile file(m_filePath);
        if(file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&file);

            out << QString(mainEdit.toPlainText());

            file.close();

            setWindowTitle("NotePad - [" + m_filePath + "]");
        }
        else
        {
            showErrorMessage(QString("Open file Error!\n\n") + "\"" + m_filePath + "\"");
            m_filePath = "";
        }
    }

}

void MainWindow::onFileSaveAs()
{
    QString path = showFileDialog(QFileDialog::AcceptSave, "Save As");
    if(path != "")
    {
        QFile file(path);

        if(file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&file);

            out << QString(mainEdit.toPlainText());

            file.close();

            m_filePath = path;

            setWindowTitle("NotePad - [" + m_filePath + "]");

        }
        else
        {
            showErrorMessage(QString("Open file Error!\n\n") + "\"" + path + "\"");
        }
    }


}
MainWindowSlots.cpp
技术分享
#include <QtGui/QApplication>
#include "MainWindow.h"
#include <QTextCodec>


int main(int argc, char *argv[])
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); //路径名支持中文
    QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK")); //QString支持中文
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK")); //string支持中文
    QApplication a(argc, argv);
    MainWindow* w = MainWindow::NewInstance();
    int ret = -1;
    if(w != NULL)
    {
        w->show();
        ret = a.exec();
    }

    delete w;
    return ret;
}
main.cpp

三、小结

(1)、Qt项目中尽量将界面代码与功能代码分离开

(2)、Qt项目开发中尽量复用平台中提供的相关组件

(3)、Qt项目中的多数情况都是编写相应的槽函数

A、槽函数用于响应用户操作

B、槽函数是具体功能的触发点

第三十五课、文本编辑器中的数据存取