QTextEdit:如何修改粘贴到编辑器中的文本?

时间:2018-12-08 23:17:08

标签: c++ qt qt5

当用户将文本粘贴到QTextEdit小部件中时,我想用空格替换制表符。我希望会有类似onPaste(QString&)的信号,但似乎没有这样的信号。这可能吗?

1 个答案:

答案 0 :(得分:2)

由于LogicStuff的评论,我能够自己制作一个从QTextEdit派生的新类来弄清楚它。

editor.hpp:

#pragma once
#include <QTextEdit>

class Editor : public QTextEdit
{
    Q_OBJECT

public:
    Editor(QWidget * parent) : QTextEdit(parent) {}

    void insertFromMimeData(const QMimeData * source) override;

private:
    static const int TAB_SPACES = 4;
};

editor.cpp:

#include "editor.hpp"
#include <QMimeData>

void Editor::insertFromMimeData(const QMimeData * source)
{
    if (source->hasText())
    {
        QString text = source->text();
        QTextCursor cursor = textCursor();

        for (int x = 0, pos = cursor.positionInBlock(); x < text.size(); x++, pos++)
        {
            if (text[x] == '\t')
            {
                text[x] = ' ';
                for (int spaces = TAB_SPACES - (pos % TAB_SPACES) - 1; spaces > 0; spaces--)
                    text.insert(x, ' ');
            }
            else if (text[x] == '\n')
            {
                pos = -1;
            }
        }
        cursor.insertText(text);
    }
}