1. 程式人生 > >qt文字編輯器

qt文字編輯器

QQ:609162385
https://blog.csdn.net/cqltbe131421
在這裡插入圖片描述

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTextCharFormat>
#include <QLineEdit>
#include <QPushButton>
#include <QCheckBox>
#include <QLabel>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    void InitForm();
    void mergeFormatOnWordOrSelection(const QTextCharFormat &format);
    void colorChanged(const QColor &c);
protected:
    void closeEvent(QCloseEvent *e);

private:
    bool maybeSave();
    void setCurrentFileName(const QString &fileName);//設定當前檔案的名稱
    bool fileSave();
    bool fileSaveAs();
    bool load(const QString &f);
    void fileOpen();
    
private slots:

    void on_actionopen_triggered();

    void on_actionsave_triggered();

    void on_actioncnew_triggered();

    void on_actionfont_triggered();

    void on_actionsaveas_triggered();

    void on_actioncolor_triggered();

    void on_actionprint_triggered();

    void on_actionabouttext_triggered();

    void on_actionaboutauthor_triggered();

    void on_actiontimedata_triggered();

    void on_actionexit_triggered();

    void on_action_PDF_triggered();

    void on_tbnBold_clicked(bool checked);

    void on_tbnUnderline_clicked(bool checked);

    void on_tbnItalic_clicked(bool checked);

    void currentFormatChanged(const QTextCharFormat &format);

    void on_fontComboBox_currentFontChanged(const QFont &f);

    void on_tbnColor_clicked();


    void on_fontsizecomboBox_currentIndexChanged(const QString size);

    void on_actionfind_triggered();

    void showFindText();

    void on_textEdit_textChanged();

    void showCursorPosition();//顯示當前文字位置的槽函式

private:
    Ui::MainWindow *ui;

    QColor color;
    QString fileName;

    QDialog *findDialog;
    QLineEdit *find_Text_LineEdit;//宣告一個行編輯器,用於輸入要查詢的內容
    QCheckBox *findcheckbox;
    QPushButton *find_Next_Button;

    //狀態列的一些操作
    QLabel *firstlabel;
    QLabel *secondlabel;
    QLabel *permanent;//顯示永久資訊標籤
    void Initstatusbar();
};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog.h>
#include <QIODevice>
#include <QDebug>
#include <QTextStream>
#include <QMessageBox>
#include <QFontDialog>
#include <QColorDialog>
#include <QTextDocument>
#include <QPrintDialog>
#include <QPrinter>
#include <QDateTime>

#include "app/frmmessagebox.h"
#include "app/myhelper.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //setAttribute(Qt::WA_DeleteOnClose);//當住視窗關閉時其他空間也會自己進行銷燬
    this->InitForm();
    this->Initstatusbar();
}

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

/*
 *函式功能:引數出事後操作
*/
void MainWindow::InitForm()
{
    //this->setCentralWidget(ui->textEdit);//設定輸入文字框為中央顯示
    //ui->statusBar->showMessage("歡迎訪問Kelvin的記事本",2000);
    fileName = "609162385.txt";
    this->setWindowTitle(fileName);     //設定對話方塊標題
    ui->textEdit->setFocus();
    connect(ui->actioncopy,SIGNAL(triggered()),ui->textEdit,SLOT(copy()));//複製功能的實現
    connect(ui->actionpaste,SIGNAL(triggered()),ui->textEdit,SLOT(paste()));//貼上功能的實現
    connect(ui->actionaboutQT,SIGNAL(triggered()),qApp,SLOT(aboutQt()));//關於QT
    connect(ui->actionundo, SIGNAL(triggered()), ui->textEdit, SLOT(undo()));//撤銷功能的實現
    connect(ui->actionredo, SIGNAL(triggered()), ui->textEdit, SLOT(redo()));//恢復功能實現
    connect(ui->actioncut, SIGNAL(triggered()), ui->textEdit, SLOT(cut()));//剪下功能的實現

    connect(ui->textEdit,SIGNAL(currentCharFormatChanged(QTextCharFormat)),this,SLOT(currentFormatChanged(const QTextCharFormat)));
    connect(ui->textEdit,SIGNAL(cursorPositionChanged()),this,SLOT(showCursorPosition()));
    ui->actionsave->setEnabled(false);
    ui->actioncopy->setEnabled(false);
    ui->actioncut->setEnabled(false);
    ui->actionredo->setEnabled(false);
    ui->actionundo->setEnabled(false);
}

void MainWindow::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
{
    QTextCursor cursor = ui->textEdit->textCursor();
    if (!cursor.hasSelection())
        cursor.select(QTextCursor::WordUnderCursor);
    cursor.mergeCharFormat(format);
    ui->textEdit->mergeCurrentCharFormat(format);
}

void MainWindow::colorChanged(const QColor &c)
{
    QPixmap pix(16,16);
    pix.fill(c);
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    if(maybeSave())
    {
        e->accept();
    }
    else
    {
        e->ignore();
    }
}

bool MainWindow::maybeSave()
{
    if(!ui->textEdit->document()->isModified())
    {
        return true;
    }
    if(fileName.startsWith(":/"))
        return true;
    int ok = myHelper::ShowMessageBoxQuesion(tr("檔案已經被修改,是否要儲存?"));
    if(ok == 1)
    {
        fileSave();
    }
    else if(ok == 2)
    {
        qApp->exit();
    }
    else
    {
        return false;
    }
    return true;
}

/*
 *函式功能:設定文字的名稱
 *輸入引數:檔案的名稱
*/
void MainWindow::setCurrentFileName(const QString &fileName)
{
    this->fileName = fileName;
    ui->textEdit->document()->setModified(false);

    QString shownName;
    if (fileName.isEmpty())
    {

        shownName = "untitled.txt";
    }
    else
        shownName = QFileInfo(fileName).fileName();

    setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text")));
    //setWindowModified(false);
}

bool MainWindow::fileSave()
{
    if(fileName.isEmpty())
    {
        fileSaveAs();
    }

    QTextDocumentWriter writer(fileName);
    bool success = writer.write(ui->textEdit->document());
    if (success)
        ui->textEdit->document()->setModified(false);
    return success;
}

bool MainWindow::fileSaveAs()
{
    QString fn = QFileDialog::getSaveFileName(this, tr("另存為..."),
                                              QString(), tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;(*.h);;(*.cpp);;(*.txt);;All Files (*)"));
    if (fn.isEmpty())
        return false;
    if (! (fn.endsWith(".txt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) )
        fn += ".txt"; // default
    setCurrentFileName(fn);
    return fileSave();
}

bool MainWindow::load(const QString &f)
{
    if(!QFile::exists(f))
    {
        return false;
    }
    QFile file (f);
    if(!file.open(QFile::ReadOnly))
    {
        return false;
    }
    QByteArray data = file.readAll();
    QTextCodec *codec = Qt::codecForHtml(data);
    QString str = codec->toUnicode(data);
    if(Qt::mightBeRichText(str))
    {
        ui->textEdit->setHtml(str);
    }
    else
    {
        ui->textEdit->setPlainText(str);
    }

    setCurrentFileName(str);
    return true;
}

void MainWindow::fileOpen()
{
    QString fn = QFileDialog::getOpenFileName(this, tr("開啟檔案..."),
                                              QString(), tr("HTML-Files (*.htm *.html);;All Files (*)"));
    if(!fn.isEmpty())
    {
        load(fn);
    }
}

/*
 *函式功能:開啟檔案
*/
void MainWindow::on_actionopen_triggered() //開啟檔案功能實現
{
    if(ui->textEdit->document()->isModified())
    {
        int ok = myHelper::ShowMessageBoxQuesion(tr("是否要儲存當前檔案?"));

        if(ok == 1)
        {
            on_actionsave_triggered();
        }
        else if(ok == 2)
        {
            ui->textEdit->clear();

            fileName = QFileDialog::getOpenFileName(this,
                                                    tr("開啟檔案"), "", tr("檔案 (*.c *.cpp *.h);;(*.txt);;All Files (*)"));

            QFile file(fileName);//開啟檔案失敗情況
            if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                qDebug()<<"Can't open the file!"<<endl;
                return ;
            }

            QTextStream in(&file);
            ui->textEdit->setText(in.readAll());//讀取檔案全部內容
        }
        else
        {
            return;
        }

    }
    else
    {
        fileName = QFileDialog::getOpenFileName(this,
                                                tr("開啟檔案"), "", tr("檔案 (*.c *.cpp *.h);;(*.txt);;All Files (*)"));

        QFile file(fileName);//開啟檔案失敗情況
        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qDebug()<<"Can't open the file!"<<endl;
            return ;
        }

        QTextStream in(&file);
        ui->textEdit->setText(in.readAll());//讀取檔案全部內容
    }
}

/*
 *函式功能:儲存功能
*/
void MainWindow::on_actionsave_triggered()
{
    fileSaveAs();
//    if(fileName.isEmpty())
//    {

//        return;
//    }
//    QFile file(fileName);//開啟檔案失敗情況
//    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
//    {
//        qDebug()<<"Can't open the file!"<<endl;
//        return ;
//    }

//    QTextStream out(&file);
//    out << ui->textEdit->toPlainText();
//    ui->statusBar->showMessage("save file ok!",3000);
}

/*
 *函式功能:新建檔案
 *說明:用來新建立一個Txt文字,新建之前進行判斷 當前TextEdit內是否有內容,分別進行相應的操作
*/
void MainWindow::on_actioncnew_triggered()
{
    if(maybeSave())
    {
        ui->textEdit->clear();
        setCurrentFileName(QString());
    }
}

/*
 *函式功能:字型設定
 *說明:對當前字型的字型進行設定
*/
void MainWindow::on_actionfont_triggered()
{
    bool ok;
    QFont font = QFontDialog::getFont(
                &ok, QFont("Helvetica [Cronyx]", 10), this);
    if (ok)
    {
        // the user clicked OK and font is set to the font the user selected
        ui->textEdit->setFont(font);
    }
    else
    {
        // the user canceled the dialog; font is set to the initial
        // value, in this case Helvetica [Cronyx], 10
    }
}


/*
 *函式功能:另存為功能的實現
 *說明:將當前檔案進行另存為
*/
void MainWindow::on_actionsaveas_triggered()
{
    fileSaveAs();
    //    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
    //                                                    "untitled.txt",
    //                                                    tr("Files (*.cpp *.h *.c)"));
    //    QFile file(fileName);
    //    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    //        return;

    //    QTextStream out(&file);
    //    out << ui->textEdit->toPlainText();
    //    ui->statusBar->showMessage("Save File OK!", 3000);

}

/*
 *函式功能:設定當前文字的顏色
*/
void MainWindow::on_actioncolor_triggered()
{
    QColor color(255,255,255);

    QColor col = QColorDialog::getColor(color, this, "Select Color");

    if(!col.isValid())
        return;
    QTextCharFormat fmt;
    fmt.setForeground(col);
    mergeFormatOnWordOrSelection(fmt);
    colorChanged(col);
}

/*
 *函式功能:列印當前的文字
 *說明:呼叫Qprinter 利用系統的列印機制,將當前文字打印出來
*/
void MainWindow::on_actionprint_triggered()//列印功能的實現
{
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog *dlg = new QPrintDialog(&printer, this);
    if (ui->textEdit->textCursor().hasSelection())
        dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
    dlg->setWindowTitle(tr("Print Document"));
    if (dlg->exec() == QDialog::Accepted)
    {
        ui->textEdit->print(&printer);
    }
    delete dlg;
}

/*
 *函式功能:顯示記事本的版權等資訊介面
*/
void MainWindow::on_actionabouttext_triggered() //關於記事本的資訊
{
    QMessageBox::about(this,tr("about"),tr("The software is created by LiQi!"
                                           "and The Notepad to create time for April 29, 2014,"
                                           "Please respect the copyright information"));

}

/*
 *函式功能:關於作者的一些資訊顯示介面
*/
void MainWindow::on_actionaboutauthor_triggered()
{
    QMessageBox::about(this,tr("about"),tr("About the author:"
                                           "The author is a student of Taiyuan Institute of technology,"
                                           "is a professional computer system, network engineering,"
                                           "write this notebook is to learn to QT since the exercise yourself this time."));
}

void MainWindow::on_actiontimedata_triggered()
{
    QDateTime now = QDateTime::currentDateTime();
    QDateTime xmas(QDate(now.date().year(), 12, 25), QTime(0, 0));
    qDebug("There are %d seconds to Christmas", now.secsTo(xmas));
}

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

/*
 *函式功能:將文字內容轉換成PDF文件
*/
void MainWindow::on_action_PDF_triggered()
{
#ifndef QT_NO_PRINTER
    QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
                                                    QString(), "*.pdf");
    if (!fileName.isEmpty())
    {
        if (QFileInfo(fileName).suffix().isEmpty())
            fileName.append(".pdf");
        QPrinter printer(QPrinter::HighResolution);
        printer.setOutputFormat(QPrinter::PdfFormat);
        printer.setOutputFileName(fileName);
        ui->textEdit->document()->print(&printer);
    }
#endif
}

void MainWindow::on_tbnBold_clicked(bool checked)
{
    if(checked)
    {
        ui->textEdit->setFontWeight(QFont::Bold);
    }
    else
    {
        ui->textEdit->setFontWeight(QFont::Normal);
    }
    ui->textEdit->setFocus();
}

/*
 *函式功能:給文字新增下劃線
*/
void MainWindow::on_tbnUnderline_clicked(bool checked)
{
    ui->textEdit->setFontUnderline(checked);
    ui->textEdit->setFocus();
}

/*
 *函式功能:使字型字型傾斜
*/
void MainWindow::on_tbnItalic_clicked(bool checked)
{
    ui->textEdit->setFontItalic(checked);
    ui->textEdit->setFocus();
}

void MainWindow::currentFormatChanged(const QTextCharFormat &format)
{
    //當編輯器的字型格式改變時,我們讓部件狀態也隨之改變
    ui->fontComboBox->setCurrentFont(format.font());

    if(format.fontPointSize()<9)  //如果字型大小出錯,因為我們最小的字型為9
        ui->fontsizecomboBox->setCurrentIndex(3); //即顯示12
    else ui->fontsizecomboBox->setCurrentIndex(
                ui->fontsizecomboBox->findText(QString::number(format.fontPointSize())));

    ui->tbnBold->setChecked(format.font().bold());
    ui->tbnItalic->setChecked(format.font().italic());
    ui->tbnUnderline->setChecked(format.font().underline());
    color = format.foreground().color();

    ui->textEdit->setFocus();
}

/*
 *函式功能:當前字型變化時的操作
*/
void MainWindow::on_fontComboBox_currentFontChanged(const QFont &f)
{
    ui->textEdit->setCurrentFont(f);
    ui->textEdit->setFocus();
}

/*
 *函式功能:對當前文字進行顏色設定
 *說明:當點選給按鈕時彈出顏色框,提供選擇
*/
void MainWindow::on_tbnColor_clicked()
{
    color = QColorDialog::getColor(color,this);
    if(color.isValid())
    {
        ui->textEdit->setTextColor(color);
        ui->textEdit->setFocus();
    }
}

/*
 *函式功能:當comBobox中選擇的大小改變時相應的改變文字的大小
*/
void MainWindow::on_fontsizecomboBox_currentIndexChanged(const QString size)
{
    ui->textEdit->setFontPointSize(size.toDouble());
    ui->textEdit->setFocus();
}

/*
 *函式功能:實現查詢功能
*/
void MainWindow::on_actionfind_triggered()
{
    findDialog = new QDialog(this);
    findDialog->setWindowTitle(tr("查詢"));
    findDialog->setMinimumSize(300,130);
    findDialog->setMaximumSize(300,130);

    find_Text_LineEdit = new QLineEdit(findDialog);
    find_Text_LineEdit->setMinimumSize(200,30);
    find_Text_LineEdit->setFont(QFont("Timers",20,QFont::Bold));

    find_Next_Button = new QPushButton(tr("查詢下一個."),findDialog);
    find_Next_Button->setMaximumSize(80,40);

    findcheckbox = new QCheckBox(tr("大小寫敏感."),findDialog);


    QVBoxLayout *layout = new QVBoxLayout(findDialog);
    layout->addWidget(find_Text_LineEdit,1);
    layout->addWidget(findcheckbox,3);
    layout->addWidget(find_Next_Button,7);

    findDialog->show();

    connect(find_Next_Button,SIGNAL(clicked()),this,SLOT(showFindText()));
}

/*
 *函式功能:查詢槽函式
*/
void MainWindow::showFindText()
{
    QString findTex = find_Text_LineEdit->text();
    if(!ui->textEdit->find(findTex,QTextDocument::FindBackward))
    {
        myHelper::ShowMessageBoxInfo(QString(tr("查詢,找不到 '%1'").arg(findTex)));
    }
}

/*
 *函式功能: 按鈕狀態初始化
 *說明:當有內容變化時變化時,相應初始化按鈕的狀態
*/
void MainWindow::on_textEdit_textChanged()
{
    ui->actionsave->setEnabled(true);//儲存按鈕可用
    ui->actionundo->setEnabled(true);//撤銷按鈕可用
    if(ui->actionundo->isCheckable())
    {
        ui->actionredo->setEnabled(true);
    }
}

/*
 *函式功能:獲取游標所在的位置,並顯示在狀態列中
*/
void MainWindow::showCursorPosition()
{
    int rowNum = ui->textEdit->document()->blockCount();            //獲取游標所在的行號
    const QTextCursor cursor = ui->textEdit->textCursor();
    int colNum = cursor.columnNumber();                             //獲取游標所在列的列號
    firstlabel->setText(tr("%1行 %2列").arg(rowNum).arg(colNum));    //在狀態列中顯示游標位置
}

/*
 *函式功能:狀態列的初始化
 *說明:對狀態列中新增一些標籤,進行顯示相應的資料
*/
void MainWindow::Initstatusbar()
{
    QStatusBar *statusbar = ui->statusBar;          //獲取狀態列
    firstlabel = new QLabel(this);                  //新建標籤
    firstlabel->setMinimumSize(150,20);             //設定最小尺寸
    firstlabel->setAlignment(Qt::AlignCenter);      //居中顯示
    firstlabel->setFrameShape(QFrame::WinPanel);    //設定標籤形狀
    firstlabel->setFrameShadow(QFrame::Sunken);     //標籤陰影  QFrame::Sunken - 框架和內容看起來凹陷

    secondlabel = new QLabel(this);
    secondlabel->setMinimumSize(150,20);
    secondlabel->setAlignment(Qt::AlignCenter);
    secondlabel->setFrameShape(QFrame::WinPanel);
    secondlabel->setFrameShadow(QFrame::Sunken);

    //顯示永久資訊的一些設定
    permanent = new QLabel(this);
    permanent->setFrameStyle(QFrame::Box | QFrame::Sunken);
    permanent->setText(
                tr("<a href=\"http://blog.csdn.net/u013704336\">更加精彩技術請點選kelvin的部落格</a>"));
    permanent->setTextFormat(Qt::RichText);
    permanent->setOpenExternalLinks(true);

    statusbar->addWidget(firstlabel);
    statusbar->addWidget(secondlabel);
    statusbar->addPermanentWidget(permanent);

    firstlabel->setText("歡迎使用Kelvin的記事本");             //初始化操作
    secondlabel->setText("Kelvin製作");
}