当用户将文本粘贴到QTextEdit小部件中时,我想用空格替换制表符。我希望会有一个像onPaste(QString&(这样的信号,但似乎没有这样的信号。这可能吗?
感谢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);
}
}