I am having trouble with binding a shortcut to a QPushButton
through QtCreator.
What I did is to place a button in a QDialog
and to use auto-connect to connect the clicked()
signal to a slot. I then set up the property QAbstractButton::shortcut
to Ctrl + N in the form editor.
When I click the button, the slot gets triggered, but when I press the shortcut, nothing happens.
Here is the code for the ui file :
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>PushButton</string>
</property>
<property name="shortcut">
<string>Ctrl+N</string>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
And here is the code for my Dialog class (header and source have been merged):
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0) :
QDialog(parent), ui(new Ui::Dialog)
{
ui->setupUi(this);
}
private slots:
void on_pushButton_clicked()
{
qDebug() << "click!";
}
private:
Ui::Dialog *ui;
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
Dialog dialog;
dialog.show();
return app.exec();
}
I managed to make it work with an action in the menubar, I don't understand why it does not seem to work the same.
I am using Qt 5.8.0.
You are probably working on a macOS, for which the ControlModifier
corresponds with the Command keys
and the MetaModifier
corresponds to the Control key
as documented by Qt :
Note : On macOS, the ControlModifier value corresponds to the Command keys on the Macintosh keyboard, and the MetaModifier value corresponds to the Control keys.
Also the documentation of QKeySequence
gives relevant information:
Note : On macOS, references to "Ctrl", Qt::CTRL, Qt::Key_Control and Qt::ControlModifier correspond to the Command keys on the Macintosh keyboard, and references to "Meta", Qt::META, Qt::Key_Meta and Qt::MetaModifier correspond to the Control keys.
So, you should press Command + N
to trigger the shortcut.
I got around the problem by creating a menubar action triggering the same slot as the button.
Since the shortcuts work (in my case) only with menubar actions, I believe this is a good alternative, because the button that I wanted to have a shortcut triggered one of the main slots of my application.
I did the following:
clicked()
signal to the action's triggered()
signal
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.