如何重载QLineEdit的复制和粘贴事件



我需要更改QLineEdit的复制和粘贴事件。例如,我们有一行";这行";并且我想要删除";i〃;符号-";Ths lne";。我怎样才能得到这个结果?

我试图从QLineEdit继承并重载copy((和paste((插槽,如下所示:

class CTextField : public QLineEdit
{
Q_OBJECT
public:
CTextField(QWidget *parent = 0);
virtual ~CTextField() = default;
public slots:
virtual void paste();
virtual void copy();
};

但是,当我使用CTRL+V或通过菜单项粘贴时,插槽不会调用。复制也是如此。

就我自己而言,我在重新实现QLineEdit::copy()QLineEdit::paste()插槽的所有方式中找到了解决方案:通过键序列,弹出QMenumouseReleaseEvent。对于大多数情况来说,这应该足够了。

CLineEdit.h

class CLineEdit : public QLineEdit
{
Q_OBJECT
protected:
virtual void contextMenuEvent(QContextMenuEvent *event) override
{
if (QMenu *menu = createStandardContextMenu()) {
for (auto * action : menu->actions())
{
if (disconnect(action, SIGNAL(triggered()), this, SLOT(copy())))
connect(action, SIGNAL(triggered()), this, SLOT(cleanCopy()));
if (disconnect(action, SIGNAL(triggered()), this, SLOT(paste())))
connect(action, SIGNAL(triggered()), this, SLOT(cleanPaste()));
}
menu->setAttribute(Qt::WA_DeleteOnClose);
menu->popup(event->globalPos());
}
}
virtual void keyPressEvent(QKeyEvent *event) override
{
if (event == QKeySequence::Copy)
cleanCopy();
else if (event == QKeySequence::Paste)
{
QClipboard::Mode mode = QClipboard::Clipboard;
if (event->modifiers() == (Qt::CTRL | Qt::SHIFT)
&& event->key() == Qt::Key_Insert)
mode = QClipboard::Selection;
cleanPaste(mode);
}
else if (event == QKeySequence::Cut)
cleanCut();
else
QLineEdit::keyPressEvent(event);
}
void mouseReleaseEvent(QMouseEvent* e)
{
if (e->button() == Qt::LeftButton)
cleanCopy(QClipboard::Selection);
else if (!d->control->isReadOnly() && e->button() == Qt::MiddleButton) 
{
deselect();
cleanPaste(QClipboard::Selection);
}
else
QLineEdit::mouseReleaseEvent(e);
}

protected slots:
virtual void cleanCopy(QClipboard::Mode mode = QClipboard::Clipboard)
{
// Your copy implementation
}
virtual void cleanPaste(QClipboard::Mode mode = QClipboard::Clipboard)
{
// Your paste implementation
}
virtual void cleanCut(QClipboard::Mode mode = QClipboard::Clipboard)
{
// Your cut implementation OR just:
if (hasSelectedText())
{
cleanCopy();
del();
}
}
};

相关内容

  • 没有找到相关文章

最新更新