一、简介
Qt对富文本的处理,主要有几个感兴趣的知识点才写下这篇文章,将文本或图片转换成pdf格式、文件直接拖拽到文本框中、双击对程序全屏和缩小、滚动滑轮对文字放大缩小及安装事件过滤器通过键盘的上下按键对文本放大缩小。
二、运行图
(1)运行效果图如下图1所示。

三、详解
1、文本文件转换成pdf
- void MainWindow::createPdf()
- {
- QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"),
- QString(), "*.pdf");
- if (!fileName.isEmpty()) {
-
-
- if (QFileInfo(fileName).suffix().isEmpty())
- fileName.append(".pdf");
- QPrinter printer;
-
- printer.setOutputFormat(QPrinter::PdfFormat);
- printer.setOutputFileName(fileName);
- ui->textEdit->print(&printer);
- }
- }
调用QTextEdit的print函数进行转换输出。输出效果如下图2所示。
2、拖放功能
-
- void MainWindow::dragEnterEvent(QDragEnterEvent *event)
- {
-
- if(event->mimeData()->hasUrls()) {
- event->acceptProposedAction();
- }
- else event->ignore();
- }
-
- void MainWindow::dropEvent(QDropEvent *event)
- {
-
- const QMimeData *mimeData = event->mimeData();
-
- if(mimeData->hasUrls()){
-
- QList<QUrl> urlList = mimeData->urls();
-
- QString fileName = urlList.at(0).toLocalFile();
- QFileInfo info(fileName);
-
- if(!fileName.isEmpty()){
-
- QFile file(fileName);
- if(!file.open(QIODevice::ReadOnly)) return;
-
- QTextStream in(&file);
-
- setWindowTitle(tr("文件转换:%1").arg(info.fileName()));
- ui->textEdit->setText(in.readAll());
- }
- }
- }
在此只介绍文本的简单拖放,重载两个函数 void dragEnterEvent(QDragEnterEvent *event); //拖动进入事件void dropEvent(QDropEvent *event); //放下事件,实现拖动文件到多信息文本编辑器中去,后面还会有相应的文章专门介绍文本和图片的拖放及不同程序间的拖放。
3、全屏
-
- void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
- {
-
- if(event->button() == Qt::LeftButton){
-
-
- if(windowState() != Qt::WindowFullScreen)
- setWindowState(Qt::WindowFullScreen);
-
-
- else setWindowState(Qt::WindowNoState);
- }
- }
鼠标双击
文本编辑器
和菜单栏外的位置都会全屏显示(全屏将隐藏菜单栏),再双击回到原来大小。
4、滚轮放大缩小
-
- void MainWindow::wheelEvent(QWheelEvent *event)
- {
-
- if(event->delta() > 0){
- ui->textEdit->zoomIn();
- }else{
- ui->textEdit->zoomOut();
- }
- }
向前滚动滑轮delta值大于0放大操作,向后滚动缩小操作,其运行如下图3所示。

5、方向键上下放大缩小
在MainWindow上为lineEdit安装事件过滤器, ui->textEdit->installEventFilter(this);
- bool MainWindow::eventFilter(QObject *obj, QEvent *event)
- {
-
-
- if(obj == ui->textEdit){
- if(event->type() == QEvent::KeyPress) {
- QKeyEvent *kevent = dynamic_cast<QKeyEvent *>(event);
- if (kevent->key() == Qt::Key_Down) {
- ui->textEdit->zoomOut();
- }
- else if(kevent->key() == Qt::Key_Up) {
- ui->textEdit->zoomIn();
- }
- }
- }
- return QMainWindow::eventFilter(obj,event);
- }
捕获方向键的上下按键进行放大缩小操作。其运行如下图3所示。

四、总结
(1)有乱码问题时,在windows下使用QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));Linux下使用QTextCodec::setCodecForTr(QTextCodec::codecForName("gb2312"));
(2)编译错误时,先删除.pro.user文件,重新打开编译。或直接使用命令行编译。
(3)源码已经打包上传到csdn上可登录下载(http://download.youkuaiyun.com/detail/taiyang1987912/7560697)。