Search code examples
menupyqtpyqt4copy-pastecustom-widgets

PyQt: Global copy/paste actions for custom widgets


I'm writing a tool which has a big custom text area widget and a lot of other text input widgets, etc. I'm currently working with adding copy/paste to my tool and got stuck on how to do this on a global level - i.e. I don't want to implement copy/paste locally in every widget that needs it. For Qt standard widgets it just works to use copy/paste with Ctrl+C/Ctrl+V, but of course I have to implement it manually for my custom widgets.

But what about copy/paste actions in the menu bar? Do I have to connect them to every widget that exists in my program, or is there some better built in way to do this? I would prefer if I could just connect the menu actions to some global copy/paste handler that notifies the widget in focus automatically.


Solution

  • There is no generic copy/paste functionality - for custom widgets, you will have to implement everything yourself. The QClipboard class provides access to the system clipboard. Every application has a single clipboard object, which can be accessed via QApplication.clipboard() or qApp.clipboard().

    The standard Qt input widgets all define their own copy() and paste() slots that can be connected to menu actions, toolbar buttons, keyboard shortcuts, etc. So your custom widgets should probably define the same interface.

    There are classes such as QActionGroup, QButtonGroup, and QSignalMapper that provide support for centralised signal handling, but it is often much simpler to stick with explicit, one-to-one connections.