[Qt-interest] QShortCut and QMenu

Josh jnfo-c at grauman.com
Sat Feb 21 23:57:27 CET 2009


Hello,

This should be simple, but I haven't figured it out yet. I'm trying to get 
Shortcuts to work from within a context menu. The following code is a 
complete minimal example. The menu shows up fine when you right click the 
TextEdit and the menu1() function gets called, but the ShortCut key 
combination (Ctrl+Y) doesn't do anything. What am I missing? Thanks.

In addition, if there is documentation that helps me understand how key 
presses 'travel' through Qt, that would be helpful. I'm not sure what 
order events pass through the system (Ie. with reference to event filters, 
reimplementing keyPressEvent functions, shortcut keys, etc. for parent and 
child widgets, the main app, ...)

Josh



#include <QMenu>
#include <QApplication>
#include <QTextEdit>
#include <QContextMenuEvent>

class TextEdit : public QTextEdit
{
     Q_OBJECT

public:
     TextEdit(QWidget *parent =0);
     ~TextEdit(void);

protected:
     void contextMenuEvent(QContextMenuEvent *event);

private:
     QMenu *menu;

private slots:
     void menu1(void);
};

TextEdit::TextEdit(QWidget *parent) : QTextEdit(parent)
{
   menu=new QMenu(this);
   menu->addAction("My Menu Item1", this, SLOT(menu1()),QKeySequence(Qt::CTRL + Qt::Key_Y));
}

TextEdit::~TextEdit(void)
{
   delete menu;
}

void TextEdit::menu1(void)
{
   printf("Menu Activated\n");
}

void TextEdit::contextMenuEvent(QContextMenuEvent *event)
{
   menu->exec(event->globalPos());
}

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   TextEdit *te = new TextEdit;
   te->show();
   return app.exec();
}

#include "main.moc"



More information about the Qt-interest-old mailing list