Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

how to set "Ctrl + c" for copy shortcut on a QMainWindow?



  • Hi, I am working on a QMainWindow and need to catch "ctrl +c" to operate copy of some data on it.

    class MainWindow(QMainWindow):
        def __init__(self) -> None:
    

    I have made a menuBar and add QAction with "Ctrl + c" shortcut to it:

      def _create_menu(self):
    
            file_menu = self.menuBar().addMenu("&File")
    
            copy_data = QAction(text="&Copy", parent=self)
            #copy_data.setShortcut("Ctrl+c")
            copy_data.setShortcut(Qt.CTRL + Qt.Key_C)
            copy_data.triggered.connect(self._on_copy_data)
    
             file_menu.addAction(copy_data)
    
    

    and
    create my function

        def _on_copy_data(self):
            self._bits_widget.copy()
    

    But when I pressed on "Ctrl+c" _on_copy_data function didn't triggered.
    When I use the menu bar and click on copy it's will be triggered.

    Where is my mistake when I use other combine of keys like "Ctrl + l" it will work also.

    I use Pyqt5 in ubuntu OS
    Thanks



  • Hello,

    I'm not sure about whether it's the best idea or not, but I personally do it this way:

    QAction* lInfoRowAction = new QAction("info", this);
    lInfoRowAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_I));
    addAction(lInfoRowAction);
    connect(lInfoRowAction, SIGNAL(triggered()), this, SLOT(showInfoGeneral()));

    Directly in a function in a class that inherits QMainWindow. This way, the shortcut will be global to the window.



  • Thanks,
    But my problem is for "Ctrl + C" in python , "Ctrl + l" work for me.



  • @Herzl-Sh
    Are you focusing any widget (like a QLineEdit) inside your window? Because you could end up having an "ambiguous shortcut" warning if the widget already has the same shortcut.



  • @DJaq yes I have spinboxs. How can I to unfocus them?
    there exist a child that Inherited from widget can focus to it and grab the ctrl + c there?
    how I can to do it?


  • Lifetime Qt Champion



  • Because we had declarations of shortcuts littered all over the place we came up with the following solution to handle them in one place.

    We derived a class MyApplication from QApplication and overrode bool notify(QObject *receiver, QEvent *e) override. Within this function we checked e->type() == QEvent::Shortcut. Everything that couldn't be handled is then forwarded to QApplication::notify.

    We didn't override the Ctrl+C shortcut or anything similar. However, because this is so early in Qt's signal handling you could be lucky with this approach.