[Interest] Application wide shortcuts in QML?

Mark markg85 at gmail.com
Tue Nov 27 23:02:01 CET 2012


On Tue, Nov 27, 2012 at 10:08 PM, Mark <markg85 at gmail.com> wrote:
> Hi,
>
> In Qt you have QShortcut to make application wide shortcuts. However,
> QShortcut required a QWidget to work. That kinda prevents me to map
> QShortcut to a QML element because i don't have a QWidget in there.
>
> Does anyone know how i can get application wide shortcuts in QML?
>
> What i can do (as a workaround) is registering the shortcuts in C++
> and then just sending a signal to QML when one of the requested
> shortcuts has been pressed. That will likely work, but i rather
> prevent such hacks if possible :)
>
> Kind regards,
> Mark

Oh wow!
I was "trying" to be smart and just forcefully cast the
QDeclarativeItem (from which you inherit when you make a custom QML
component) to a QWidget because the code of QShortcut doesn't "seem"
to do anything with the widget specifics so i thought: "oh well, i
just cast it to a QWidget :p".

Sadly that turned out to be a lost cause. Didn't work.
What i've done now is making a global static singleton class in which
i register the main window (which inherits from QWidget). Then in the
QML plugin i simply do this:

Shortcut::Shortcut(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    m_shortcut = new QShortcut(Util::instance()->mainWindow());
    QObject::connect(m_shortcut, SIGNAL(activated()), this,
SIGNAL(activated()));
}

Util is my singleton. mainWindow calls the mainWindow widget. This
actually works! In QML i can now do:
Schortcut {
    key: Qt.Key_Backspace
    onActivated: {
        console.log("Backspace pressed.")
    }
}

This works very nice, no issue at all and works in the app wide scope.
No matter which object has focus.

Please do note, this is my workaround! It works because my application
and this component are in one codebase thus i can simply use the
qmlviewer as mainwindow. This wouldn't work if you make an actual
plugin project since that doesn't have a man window. So i'm still
searching for a clean way to do the same but without the QWidget
requirement.



More information about the Interest mailing list