views:

219

answers:

3

I am attempting to re-implement the Copy behavior for a QTextEdit object. The custom context menu I create works as expected when the 'Copy' button is clicked, but Ctrl+C isn't being handled correctly. Since the context menu doesn't have any issues, I'll omit that portion of the code.

// Create a text edit box for text editing
QTextEdit text_edit_box = new QTextEdit(getBaseWidget());

text_edit_copy_action = new QAction(QString("Copy"), getBaseWidget());
text_edit_copy_action->setShortcut(QKeySequence::Copy);

// Add custom copy action to the text edit box to ensure Ctrl+C uses our copy
// implementation
text_edit_box->addAction(text_edit_copy_action);

When I set the shortcut to be an unused key combination (e.g., Ctrl+Q) it works fine. It seems Ctrl+C is being handled differently since it's "built in".

A: 

It might be simpler to derive from QTextEdit and reimplement QTextEdit::copy(), depending on what the new behaviour is.

swongu
+3  A: 

Copy is not virtual so this might be problematic. Copying is handled via the private text control API, and is not easily accessible. The best approach is probably to install an event handler for the text edit and intercept the copy key event before it's delivered to the text control processEvent handler - which should allow your own action to correctly trigger.

Henrik Hartz
A: 

I would recommend creating an event filter and installing that on the base widget (or even the QApplication instance). You can use the event filter to look at key events and hopefully see the Ctrl+C event prior to it being handled elsewhere.

When you encounter the Ctrl+C event that you want to handle, make sure to accept that event to prevent it from being propogated any further.

Joe Corkery
Just what I said - except you actually need to "capture" it or it will be delivered to the text control and handled as a normal copy
Henrik Hartz