问题
I have the following code:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
mUi(new Ui::MainWindow)
{
mUi->setupUi(this);
this->setFixedSize(this->width(), this->height());
StyleUi();
auto closeAct = new QAction(this);
closeAct->setShortcut(QKeySequence("Ctrl+O"));
connect(closeAct, SIGNAL(activated()), this, SLOT(close()));
closeAct->setShortcutContext(Qt::ApplicationShortcut);
addAction(closeAct);
}
The last 5 lines define a QAction with a shortcut created from the sequence Ctrl+O, connects the QAction the the slot Close(). I've found this example here on stackoverflow and several other documentation sites describe what I want to do as such. However, I am not getting anywhere with this. My program doesn't close when I hit Ctrl+O. Any suggestions on where I am doing something wrong?
回答1:
You can create it by using the multiple arguments constructor for QKeySequence.
like this:
QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_O), this);
shortcut->setContext(Qt::ApplicationShortcut);
And try this to get QShortcut signal activated:
connect(shortcut, &QShortcut::activated, this, &MainApp::activeShortcut);
void MainApp::activeShortcut()
{
this->close();
}
This is a sample project for your question on github download here.
来源:https://stackoverflow.com/questions/46072018/how-do-i-add-a-custom-applicationshortcut-in-qt