QShortcut doesn't work
I cannot get the shortcut to work. Here is the code:
class Interface : public QObject
{
Q_OBJECT
private:
QMainWindow myWindow;
QWidget mainWidget;
QShortcut shortcut;
public:
Interface();
~Interface();
void show(void);
public slots:
void haha(void);
};
Interface::Interface() :
QObject(),
shortcut(QKeySequence(Qt::Key_Enter), &mainWidget)
{
myWindow.setFixedSize(1200, 600);
myWindow.setCentralWidget(&mainWidget);
QObject::connect(&shortcut, SIGNAL(activated()), this, SLOT(haha()));
}
void Interface::show(void)
{
myWindow.show();
}
void Interface::haha(void)
{
std::cout << "foo" << std::endl;
}
My main function:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
Interface myInterface;
myInterface.Show();
return app.exec();
}
It compiles without any warnings / errors, but when I execute it, pressing "Enter" does not print "foo". I've already browsed the internet, but I didn't find something close enough. Sorry if I missed something important.
+3
source to share
1 answer
Qt::Key_Enter
refers to the key located on the keyboard. You should use Qt::Key_Return
if you want the slot to be called when the main Enter key on your keyboard is pressed:
Interface::Interface() :
QObject(),
shortcut(QKeySequence(Qt::Key_Return), &mainWidget)
{
myWindow.setFixedSize(1200, 600);
myWindow.setCentralWidget(&mainWidget);
QObject::connect(&shortcut, SIGNAL(activated()), this, SLOT(haha()));
}
+4
source to share