On Qt widgets like DoubleSpinBox or ComboBox like I have a right click menu

I have several combo-boxes and double spin boxes on my Qt Dialog. Now I need “ResetToDefault” in the menu that appears when you right-click on a widget (arrow box or combo box).

How do I get this. Is there a way that I can create a custom menu that appears when I right-click or is there a way to add items to the menu that appears by right-clicking.

+3
source share
2 answers

Firstly, for Qt4, the easiest way is to create an action to reset the data and add its widget using the method addAction(or using the constructor). Then set the attribute contextMenuPolicyto Qt::ActionsContextMenu. A context menu will appear and the action will be launched.

Code example:

QAction *reset_act = new QAction("Reset to default");
mywidget->addAction(reset_act);
mywidget->setContextMenuPolicy(Qt::ActionsContextMenu);
// here connect the 'triggered' signal to some slot

For Qt3, you may need to intercept the context menu event and thus inherit QSpinBox and others. Or maybe you can intercept the context menu event from the main window, determine if this happened on widgets that should have a context menu (using the method QWidget::childAt) and show it there. But you have to test.

+5
source

Qt4 QComboBox, QLineEdit. QLineEdit, contextMenuEvent

class MyLineEdit : public QLineEdit
{
    Q_OBJECT
public:

    MyLineEdit(QWidget* parent = 0) : QLineEdit(parent){}

    void contextMenuEvent(QContextMenuEvent *event)
    {
        QPointer<QMenu> menu = createStandardContextMenu();
        //add your actions here
        menu->exec(event->globalPos());
        delete menu;
    }

};

setLineEdit QComboBox,

MyLineEdit* edit = new MyLineEdit();
comboBox->setLineEdit(edit);

. createStandardContextMenu , , contextMenuEvent, .

QComboBox , , Qt:: ActionsContextMenu .

QAbstractSpinBox setLineEdit, . - setLineEdit QAbstractSpinBox, public QLineEdit.

+1

Source: https://habr.com/ru/post/1698139/


All Articles