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

tgu*_*uen 2 c++ qt qt5

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

tgu*_*uen 5

感谢 LogicStuff 的评论,我能够通过创建一个从 QTextEdit 派生的新类来自己弄清楚。

编辑器.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;
};
Run Code Online (Sandbox Code Playgroud)

编辑器.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);
    }
}
Run Code Online (Sandbox Code Playgroud)