How disable copy and paste on QLineEdit
-
How disable copy and paste on QLineEdit?
-
Generally speaking I would discourage this kind of thing as it can be incredibly annoying for the user. Saying that, I have been in a situation where I had no choice so developed the following simple class:
#include <QtGui/QLineEdit> #include <QtGui/QKeyEvent> class LineEdit : public QLineEdit { Q_OBJECT public: LineEdit(QWidget *parent=0) : QLineEdit(parent){ init(); } LineEdit(const QString &contents, QWidget *parent=0) : QLineEdit(contents,parent){ init(); } private: void init(){ setAcceptDrops(false); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showMenu(QPoint))); } protected: void keyPressEvent(QKeyEvent *event){ if(event->matches(QKeySequence::Copy) || event->matches(QKeySequence::Cut) || event->matches(QKeySequence::Paste)) event->ignore(); else return QLineEdit::keyPressEvent(event); } private slots: void showMenu(QPoint position){} };
It basically works by:
- Catching the "QKeyEvent":http://qt-project.org/doc/qt-4.8/qkeyevent.html for the copy, cut and paste "QKeySequences":http://qt-project.org/doc/qt-4.8/qkeysequence.html and preventing there propagation,
- Preventing the user from dragging and dropping data ("setAcceptDrops":http://qt-project.org/doc/qt-4.8/qwidget.html#acceptDrops-prop), and
- Redirecting a request for a context menu to a custom slot to prevent the system menu being shown with the cut, copy and paste actions and allowing for the implementation of a custom menu.
Hope this helps ;o)
2/2