Qt Designer Shortcut to another tab

2019-06-24 05:32发布

问题:

I was wondering if it were possible to create my own shortcut key to a QTabWidget. So if I put an ampersand infront of the letter, that means that ALT+'letter' will display that tab; however, I want it so that CTRL+'letter' will display that tab (not ALT).

Is there an easy way to do this in Qt Designer? If not, is there a simple way to do it in code? QTabWidget doesn't seem to have any direct methods for setting shortcuts.

回答1:

I don't know of a way to do this via the Designer, not familiar with that. You could do it with QShortcut fairly easily in code though.

Here's a dummy widget to illustrate that. Press Ctrl+a / Ctrl+b to switch between tabs.

#include <QtGui>

class W: public QWidget
{
    Q_OBJECT

    public:
      W(QWidget *parent=0): QWidget(parent)
      {
        // Create a dummy tab widget thing
        QTabWidget *tw = new QTabWidget(this);
        QLabel *l1 = new QLabel("hello");
        QLabel *l2 = new QLabel("world");
        tw->addTab(l1, "one");
        tw->addTab(l2, "two");
        QHBoxLayout *l = new QHBoxLayout;
        l->addWidget(tw);
        setLayout(l);

        // Setup a signal mapper to avoid creating custom slots for each tab
        QSignalMapper *m = new QSignalMapper(this);

        // Setup the shortcut for the first tab
        QShortcut *s1 = new QShortcut(QKeySequence("Ctrl+a"), this);
        connect(s1, SIGNAL(activated()), m, SLOT(map()));
        m->setMapping(s1, 0);

        // Setup the shortcut for the second tab
        QShortcut *s2 = new QShortcut(QKeySequence("Ctrl+b"), this);
        connect(s2, SIGNAL(activated()), m, SLOT(map()));
        m->setMapping(s2, 1);

        // Wire the signal mapper to the tab widget index change slot
        connect(m, SIGNAL(mapped(int)), tw, SLOT(setCurrentIndex(int)));
      }
};

This isn't meant as an example of widget layout best practices... just to illustrate one way to wire a shortcut sequence to a tab change.