how to add an action to QtCore.Qt.DefaultContextMenu on Qdoublespinbox on right cilck?

后端 未结 1 679
予麋鹿
予麋鹿 2020-12-21 17:03

I have developed a fairly complex GUI tool using the Qt Designer.

For more details about the tool see: https://github.com/3fon3fonov/trifon

I have defined m

相关标签:
1条回答
  • 2020-12-21 17:38

    As we want to add a QAction to the default context menu we first overwrite the contextMenuEvent event and use a QTimer to call a function that filters the toplevels and get the QMenu that is displayed and there we add the QAction:

    doublespinbox.py

    from PyQt5 import QtCore, QtWidgets
    
    class DoubleSpinBox(QtWidgets.QDoubleSpinBox):
        minimize_signal = QtCore.pyqtSignal()
    
        def __init__(self, *args, **kwargs):
            super(DoubleSpinBox, self).__init__(*args, **kwargs)
            self.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
    
        def contextMenuEvent(self, event):
            QtCore.QTimer.singleShot(0, self.add_actions)
            super(DoubleSpinBox, self).contextMenuEvent(event)
    
        @QtCore.pyqtSlot()
        def add_actions(self):
            for w in QtWidgets.QApplication.topLevelWidgets():
                if isinstance(w, QtWidgets.QMenu) and w.objectName() == "qt_edit_menu":
                    w.addSeparator()
                    minimize_action = w.addAction("minimize this parameter")
                    minimize_action.triggered.connect(self.minimize_signal)
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = DoubleSpinBox()
        w.show()
        sys.exit(app.exec_())
    

    To use DoubleSpinBox in Qt Designer, first place doublespinbox.py next to your .ui:

    ├── ..
    ├── rvmod_gui.ui
    ├── doublespinbox.py   
    ├── ...
    

    then you must promote the widget to do so right click on the QDoubleSpinBox and select the option "Promote to ..." by adding the following to the dialog:

    Then click on the Add button and then the Promote button.

    For the other QDoubleSpinBox, right click and select the new Promote To option where the DoubleSpinBox option is.


    You can find an example here

    0 讨论(0)
提交回复
热议问题