c++qtqt5

QTextEdit: how can I modify text being pasted into editor?


When the user pastes text into the QTextEdit widget, I want to replace the tab characters with spaces. I was hoping there would be a signal like onPaste(QString &) but there doesn't appear to be anything like that. Is this possible?


Solution

  • Thanks to LogicStuff's comment, I was able to figure it out on my own by making a new class derived from 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);
        }
    }