Qt学习笔记之文本编辑器实现加粗、倾斜、下划线、字体、居中对齐、左对齐、右对齐 |
您所在的位置:网站首页 › 右侧添加下划线 › Qt学习笔记之文本编辑器实现加粗、倾斜、下划线、字体、居中对齐、左对齐、右对齐 |
一、加粗、倾斜、下划线 在实现这些功能的时候,我们首先要知道,这三个功能是要施加在所选中的字体上的,如果没有这个过程,那么这三个功能将会对所有的字符进行上述处理。所以,第一部就是要实现设置光标的选区,使格式作用于选区内的字符。 // 设置光标的选区,使格式作用于选区内的字符 void editorwindow::mergeFormat(QTextCharFormat fmt) { QTextCursor cursor = ui->textEdit->textCursor(); if (!cursor.hasSelection()) { cursor.select(QTextCursor::WordUnderCursor); } cursor.mergeCharFormat(fmt); }加粗、倾斜、下划线功能的实现 //加粗 void editorwindow::on_actionTextBold_triggered() { QTextCharFormat fmt; fmt.setFontWeight(boldcheck ? QFont::Bold : QFont::Normal); mergeFormat(fmt); boldcheck = !boldcheck; } //倾斜 void editorwindow::on_actionTextItalic_triggered() { QTextCharFormat fmt; fmt.setFontItalic(Italiccheck ? true : false); mergeFormat(fmt); Italiccheck = !Italiccheck; } //下划线 void editorwindow::on_actionTextUnderLine_triggered() { QTextCharFormat fmt; fmt.setFontUnderline(UnderLinecheck ? true : false); mergeFormat(fmt); UnderLinecheck = !UnderLinecheck; }其中boldcheck 、Italiccheck 、UnderLinecheck 是全局变量,用于检测这个功能的前一个状态,比如我选中几个字符,然后点击加粗,这几个字符就加粗了,然后我再点击加粗的时候,之前的效果取消。这就是这几个全局变量的作用。 二、字体的改变 用一下代码就可以实现改变文本字符字体的改变 //改变字体 void editorwindow::on_actionFont_triggered() { bool ok; QFont font = QFontDialog::getFont(&ok, QFont("楷体", 20), this); if(ok){ ui->textEdit->setCurrentFont(font); } }三、居中对齐、左对齐、右对齐 这三个比较简单 //左对齐 void editorwindow::on_actionLift_triggered() { ui->textEdit->setAlign\ment(Qt::AlignLeft); } //居中对齐 void editorwindow::on_actionCenter_triggered() { ui->textEdit->setAlignment(Qt::AlignCenter); } //右对齐 void editorwindow::on_actionRight_triggered() { ui->textEdit->setAlignment(Qt::AlignRight); }这三个函数能实现,光标所在的行可以实现居中对齐,左对齐,右对齐的功能。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |