Qt TextEdit富文本操作 笔记

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

头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QLabel>
#include<QFile>
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<QToolBar>
#include<QDialog>
#include<QFileDialog>
#include<QMimeData>
#include<QDropEvent>
#include<QDebug>
#include<QMessageBox>
#include<QStatusBar>
#include<QFrame>
#include<QTextFrame>
#include<QFormLayout>
#include<QHBoxLayout>
#include<QVBoxLayout>
#include<QLineEdit>
#include<QGridLayout>
#include<QPushButton>
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)
{
    QList<QUrl>urls=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());
}




  • 1
    点赞
  • 20
    收藏
  • 打赏
    打赏
  • 4
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 4

打赏作者

jayhoodlol

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

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值