Qt TextEdit富文本操作 笔记

下面代码包含了打开文件,拖拽文件,插入框架,文本块,表格,列表,图片,将所选内容变成斜体,添加下划线以及从后往前查找内容并高亮的功能。废话不多说,代码贴上:

头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include
#include
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QStatusBar *sBar;
    QLabel *label;

protected:
    void dragEnterEvent(QDragEnterEvent *event);
    void dropEvent(QDropEvent *event);
private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

源文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QToolBar *toolbar=addToolBar("toolbar");
    toolbar->addAction(ui->action_O);
    ui->textEdit->setAcceptDrops(false);
    this->setAcceptDrops(true);
    sBar=statusBar();
    label=new QLabel(this);
    sBar->addWidget(label);
    connect(ui->action_O,&QAction::triggered,
            [=]()mutable
            {
                QString path=QFileDialog::getOpenFileName(this,
                                                          "open",
                                                          "/home",
                                                          "text files(*.txt *.c *.cpp *.h)"
                                                          );
                QFile file(path);
                QFileInfo fi=QFileInfo(path);
                if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
                {
                    QMessageBox::warning(this,"ERROR",QString("read file error:%1").arg(file.errorString()));
                }
                else
                {
                QTextStream txtinput(&file);
                QString line=txtinput.readLine();
                ui->textEdit->setText("");
                ui->textEdit->append(line);
                while(!line.isNull())
                {
                    line=txtinput.readLine();
                    ui->textEdit->append(line);
                }
                label->setText(fi.fileName());
                }

            }
            );
    connect(ui->action_X,&QAction::triggered,
            [=]()mutable
            {
                QApplication *app;
                app->exit();
            }
            );

    connect(ui->action,&QAction::triggered,
            [=]()mutable
            {
//            QTextDocument *doc = ui->textEdit->document(); //获取文档对象
//            QTextFrame *rootFrame = doc->rootFrame();   //获取根框架
//            QTextFrameFormat frameFormat;           //创建框架格式
//            frameFormat.setBorderBrush(Qt::NoBrush);    //设置边界颜色
//            rootFrame->setFrameFormat(frameFormat); //给根框架使用格式
            QTextFrameFormat frameFormat2;
            frameFormat2.setBackground(Qt::green);	//设置背景色
            frameFormat2.setBorderBrush(Qt::red);
            frameFormat2.setMargin(5);		//设置边距
            frameFormat2.setPadding(5);		//设置填充
            frameFormat2.setBorder(1);//设置边界宽度为1
            frameFormat2.setBorderStyle(QTextFrameFormat::BorderStyle_Dashed);	//设置边框样式--虚线
            QTextCursor cursor = ui->textEdit->textCursor();	//获取光标
            cursor.insertFrame(frameFormat2);		//在光标处插入框架
            }
            );

    connect(ui->action_2,&QAction::triggered,
            [=]()mutable
            {
                //插入文本块
                QTextCursor cursor=ui->textEdit->textCursor();
                QTextBlockFormat blockFormat;
                blockFormat.setAlignment(Qt::AlignCenter);
                cursor.insertBlock(blockFormat);
                //字符格式,字符颜色
                QTextCharFormat charFormat;
                charFormat.setBackground(Qt::yellow);
                charFormat.setForeground(Qt::red);
                charFormat.setFont(QFont("宋体",13));
                cursor.setCharFormat(charFormat);
                cursor.insertText("新文本块");
            }
            );
    connect(ui->action_3,&QAction::triggered,
           [=]()mutable
           {
                QDialog *p=new QDialog;
                p->setWindowTitle("表格属性框");
                p->setAttribute(Qt::WA_DeleteOnClose);
                p->setWindowModality(Qt::ApplicationModal);
                QHBoxLayout *hboxLayout=new QHBoxLayout;
                QFormLayout *formLayout=new QFormLayout;
                QVBoxLayout *vboxLayout=new QVBoxLayout;
                hboxLayout->addLayout(formLayout);
                hboxLayout->addLayout(vboxLayout);
                QLabel *rowlabel=new QLabel(this);
                rowlabel->setText("行");
                QLabel *columnlabel=new QLabel(this);
                columnlabel->setText("列");
                QLabel *marginlabel=new QLabel(this);
                marginlabel->setText("外空白");//单元格与单元格之间的距离
                QLabel *paddinglabel=new QLabel(this);
                paddinglabel->setText("内空白");//单元格边界和内容之间的距离
                QLineEdit *rowline=new QLineEdit(this);
                QLineEdit *columnline=new QLineEdit(this);
                QLineEdit *marginline=new QLineEdit(this);
                QLineEdit *paddingline=new QLineEdit(this);
                formLayout->addWidget(rowlabel);
                formLayout->addWidget(rowline);
                formLayout->addWidget(columnlabel);
                formLayout->addWidget(columnline);
                formLayout->addWidget(marginlabel);
                formLayout->addWidget(marginline);
                formLayout->addWidget(paddinglabel);
                formLayout->addWidget(paddingline);
                QPushButton *pushbuttonOK=new QPushButton(this);
                pushbuttonOK->setText("确定");
                QPushButton *pushbuttonCANCLE=new QPushButton(this);
                pushbuttonCANCLE->setText("取消");
                vboxLayout->addWidget(pushbuttonOK);
                vboxLayout->addWidget(pushbuttonCANCLE);
                p->setLayout(hboxLayout);
                connect(pushbuttonOK,&QPushButton::released,
                        [=]()mutable
                        {
                           QTextCursor cursor=ui->textEdit->textCursor();
                           QTextTableFormat tableFormat;
                           tableFormat.setCellSpacing(marginline->text().toInt());
                           tableFormat.setCellPadding(paddingline->text().toInt());
                           cursor.insertTable(rowline->text().toInt(),columnline->text().toInt(),tableFormat);
                        }
                        );
                connect(pushbuttonCANCLE,&QPushButton::released,p,&QDialog::close);
                p->show();
           }
            );
    connect(ui->action_4,&QAction::triggered,
            [=]()mutable
            {
                QTextCursor cursor=ui->textEdit->textCursor();
                QTextListFormat listFormat;
                listFormat.setStyle(QTextListFormat::ListDecimal);
                cursor.insertList(listFormat);
            }
            );
    connect(ui->action_5,&QAction::triggered,
            [=]()mutable
            {
                QTextCursor cursor=ui->textEdit->textCursor();
                QTextImageFormat imageFormat;
                QString path=QFileDialog::getOpenFileName(
                                                          this,
                                                          "open",
                                                          "/home",
                                                          "image(*.png *.jpg)"
                                                         );
                imageFormat.setName(path);
                cursor.insertImage(imageFormat);
            }
            );
    QAction *italic=new QAction("斜体");
    toolbar->addAction(italic);
    QAction *underline=new QAction("下划线");
    toolbar->addAction(underline);
    QAction *search=new QAction("查找");
    toolbar->addAction(search);
    connect(italic,&QAction::triggered,
            [=]()mutable
            {
                QTextCursor cursor=ui->textEdit->textCursor();
                QTextCharFormat charFormat;
                charFormat.setFontItalic(true);
                cursor.mergeCharFormat(charFormat);
            }
            );
    connect(underline,&QAction::triggered,
            [=]()mutable
            {
                QTextCursor cursor=ui->textEdit->textCursor();
                QTextCharFormat charFormat;
                charFormat.setFontUnderline(true);
                cursor.mergeCharFormat(charFormat);
            }
            );
    connect(search,&QAction::triggered,
            [=]()mutable
            {
                QDialog *p=new QDialog;
                p->setWindowTitle("查找");
                p->setAttribute(Qt::WA_DeleteOnClose);
                p->setWindowModality(Qt::ApplicationModal);
                QLineEdit *lineEdit=new QLineEdit;
                QPushButton *pushbutton=new QPushButton;
                QVBoxLayout *vboxLayout=new QVBoxLayout;
                vboxLayout->addWidget(lineEdit);
                vboxLayout->addWidget(pushbutton);
                pushbutton->setText("查询下一个");
                connect(pushbutton,&QPushButton::released,
                        [=]()mutable
                        {
                            QString str=lineEdit->text();
                            if(ui->textEdit->find(str,QTextDocument::FindBackward))//查找后一个
                                {
                                    // 查找到后高亮显示
                                    QPalette palette = ui->textEdit->palette();
                                    palette.setColor(QPalette::Highlight,palette.color(QPalette::Active,QPalette::Highlight));
                                    ui->textEdit->setPalette(palette);
                                }
                                else
                                {
                                    QMessageBox::information(this,tr("注意"),tr("没有找到内容"),QMessageBox::Ok);
                                }
                        }
                        );
                p->setLayout(vboxLayout);
                p->show();
            }
            );

}

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

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}



void MainWindow::dropEvent(QDropEvent *event)
{
    QListurls=event->mimeData()->urls();
    if(urls.isEmpty())
        return;
    QString filename1=urls.first().toLocalFile();
    if(filename1.isEmpty())
        return;
    QFileInfo fi=QFileInfo(filename1);
    QFile file(filename1);
    file.open(QIODevice::ReadOnly|QIODevice::Text);
    QTextStream txtinput(&file);
    QString line=txtinput.readLine();
    ui->textEdit->setText("");
    ui->textEdit->append(line);
    while(!line.isNull())
    {
        line=txtinput.readLine();
        ui->textEdit->append(line);
    }
    label->setText(fi.fileName());
}




你可能感兴趣的:(QT)