• 【Qt】QTextEdit/QPlainTextEdit 实现 Tab 键多行缩进与反缩进


    【Qt】QTextEdit/QPlainTextEdit 实现 Tab 键多行缩进与反缩进

    I - 主要原理

    由于 QTextEdit 和 QPlainTextEdit ,都无法实现多行选中缩进与反缩进,选中多行后,按下缩进或反缩进,选中文本都会清空,并替换为(反)缩进或空格。因此会造成使用很不方便和低效的问题。

    需要实现一个类继承自 QTextEdit 或 QPlainTextEdit 类并重写其 keyPressEvent 接口,处理 Tab 按键

    II - 代码实现

    2.1 - 自定义类

    自定义类 TextEdit,视使用目的继承 QTextEdit 或 QPlainTextEdit,

    #include 
    // 或 #include 
    
     
    class TextEdit : public QTextEdit
    // 或 class TextEdit : public QPlainTextEdit
    {
        Q_OBJECT
    public:
        explicit TextEdit(QWidget* parent = nullptr);
    
    protected:
        void keyPressEvent(QKeyEvent *e) override; // 键盘事件
        // 添加 override 编译时检查是否重写父类函数,防止敲错
    private:
    	// 根据是否保留制表符,设置为 \t 或空格
    	QString m_indentation = "\t"; // 或 "    "
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2.2 - 实现 Tab 缩进

    需要包含头文件

    #include  // 获取光标实例
    #include  // 文本块
    
    • 1
    • 2
    void TextEdit::keyPressEvent(QKeyEvent* e)
    {
    	// 判断 Tab 按键 以及排除 Shift, Ctrl, Alt 等控制按键的情况,因为通常通过 Shift + Tab 实现反缩进
    	if (Qt::Key_Tab && Qt::NoModifier == e->modifiers())
    	{
    		// 获取光标实例
    		QTextCursor cursor = textCursor();
    		
    		// 在无选中的情况下仅插入一个缩进,并返回
    		if (!cursor.hasSelection())
    		{
    			insertPlainText(m_indentation);
    			return;
    		}  
    		
    		// 记录光标选中内容的开始和结束位置 spos(start position), epos(end position)
        	int spos = cursor.anchor();
        	int epos = cursor.position();
    
    		// 在由下向上选中时,交换开始和结束位置
    	    if(spos > epos)
    	    {
    	        int hold = spos;
    	        spos = epos;
    	        epos = hold;
    	    }
    
    		// 获取开始文本块序号
        	cursor.setPosition(spos, QTextCursor::MoveAnchor);
        	int sblock = curs.block().blockNumber();
    		// 获取结束文本块序号
        	cursor.setPosition(epos, QTextCursor::MoveAnchor);
        	int eblock = curs.block().blockNumber();
    
    		// 开始处理文本缩进
    	    cursor.setPosition(spos, QTextCursor::MoveAnchor);
    		// QTextCursor 在编辑文本块时需要调用此方法
    	    cursor.beginEditBlock();
    	    // 依次遍历所选中的文本块,并在起始处插入缩进
    	    for(int i = 0; i <= (eblock - sblock); ++i)
    	    {
    	        cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
    	        cursor.insertText(m_indentation);
    	        cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
    	    }
    		// 编辑文本块结束
        	cursor.endEditBlock();
    
    	    // 将光标的选择设置为跨越所有涉及的行,也就是说保留之前内容的选中状态,并加入缩进为选中内容。
    	    // 将光标移动至开始位置
    	    cursor.setPosition(spos, QTextCursor::MoveAnchor);
    	    cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
    	
    	    while(cursor.block().blockNumber() < eblock)
    	    {
    	    	// 使用 QTextCursor::KeepAnchor 为选中文本
    	        cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
    	    }
    	    // 移动至最后一个文本块结束位置
    	    cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    	    // 编辑器设置此光标,结束!
    	    setTextCursor(curs);
    	} // end if
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64

    2.3 - 实现反缩进

    反缩进的实现较缩进难实现,需要知道待反缩进的每一个文本行开头有多少个缩进位置,以及不足时如何处理。

    int TextEditor::GetIndentationSpaces(const QString& blockText)
    {
    	int indentationSpaceCount = 0;
    	// 遍历此文本块的每一个字符,检查是否包含空格或制表符
    	for (int i = 0; i < blockText.size() && QString("\t ").contains(blockText[i]); ++i)
    	{
    		// 若为空格
    		if (' ' == blockText[i])
    		{
    			++indentationSpaceCount;
    		}
    		else // 若为制表符 \t
    		{
    			indentationSpaceCount += tabStopDistance() / fontMetrics().averageCharWidth();
    		}
    		
    	}
    	return indentationSpaceCount;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    继续在 keyPressEvent 接口中实现 Shift + Tab 反缩进,或者也可以使用 Qt::Key_BackTab 枚举,这里使用与缩进处理文本不同的方式

    void TextEdit::keyPressEvent(QKeyEvent* e)
    {
    	// ...
    	else if (Qt::Key_BackTab == e->key())
    	{
    		// 获取光标实例
    		QTextCursor cursor = textCursor();
    		// 没有选中内容时,去除当前行的一个缩进并返回
    		if (!cursor.hasSelection())
    		{
    			int spaceCount = std::min(GetIndentationSpaces(cursor.block().text(), m_indentation.size());
    			cursor.movePosition(QTextCursor::StartOfLine); // movePosition 第二个参数缺省值为 QTextCursor::MoveMode::MoveAnchor
    			// 从行起始处删除当前的一个缩进长度
    			cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, spaceCount);
    			cursor.removeSelectedText();
    			return;
    		}
    		
    		// 记录光标选中内容的开始和结束位置 
        	int startPos = cursor.anchor();
        	int endPos = cursor.position();
    
    		// 在由下向上选中时,交换开始和结束位置
    	    if(startPos > endPos)
    	    {
    	        std::swap(startPos, endPos);
    	    }
    		
    		// 若选中内容未选中首行的全部内容,更新开始位置
    		cursor.setPosition(startPos, QTextCursor::MoveAnchor);
    		cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
    		startPos = cursor.position()
    		
    		// 重新选中
    		curosr.setPosition(endPos, QTextCursor::MoveAnchor);		
    		cursor.setPosition(startPos);
    		cursor.setPosition(endPos, QTextCursor::KeepAnchor);
    		
    		QString content = cursor.selection().toPlainText();
    		QStringList list = content.split("\n");
    		
    		// 减少开销
    		int sz = list.size();
    		for (int = 0; i < sz; ++i)
    		{
    			int spaceCount = GetIndentationSpaces(list[i]);
    			spaceCount = std::min(spaceCount, m_indentation.size());
    			// 若该行无缩进则跳过
    			if (0 == spaceCount)
    			{
    				continue;
    			}
    			// 截断
    			list[i] = list[i].mid(spaceCount); 
    		}
    		// 文本还原
    		content = list.join("\n");
    		// 移除选中文本,替换为去除缩进的文本
    		cursor.removeSelectedText();
    		cursor.insertText(content);
    			
    		// 重新使用光标选中文本,保证可连续反缩进
    		cursor.setPosition(startPos);
    		cursor.setPosition(startPos() + content.size(), QTextCursor::KeepAnchor);
    		setTextCursor(cursor);
    		
    		return;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    最后不要忘了, 调用父类的keyPressEvent ,以保证不影响其他的键盘事件

    QTextEdit::keyPressEvent(e);
    // 或
    QPlainTextEdit::keyPressEvent(e);
    
    • 1
    • 2
    • 3

    III - 参考链接

  • 相关阅读:
    从 Java 小白到收获 BAT 一线大厂offer ,分享出我这 2年的经验
    springboot基础(17):热部署
    C/C++(a/b)*c的值 2021年6月电子学会青少年软件编程(C/C++)等级考试一级真题答案解析
    光流法( Optical Flow Method)
    236. 二叉树的最近公共祖先、701. 二叉搜索树中的插入操作、450. 删除二叉搜索树中的节点
    小样本数据集 (Few-shot Learning)
    像设计师一样展示自己
    基于springboot敬老院管理系统毕业设计-附源码261535
    SQLAlchemy 连接池
    学院打卡第十天
  • 原文地址:https://blog.csdn.net/weixin_44488341/article/details/136251007