QtToolBar with underlined shortcut key in button text

穿精又带淫゛_ 提交于 2019-12-10 18:53:00

问题


I have a simple Qt toolbar with text only button Action:

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent)
{
  QToolBar* toolBar = new QToolBar(this);
  QAction*  action  = toolBar->addAction("&Action");

  QObject::connect(action, SIGNAL(triggered()), this, SLOT(onAction()));
  action->setShortcut(QKeySequence("ctrl+a"));
  addToolBar(toolBar);
}

I would like to have A in Action underlined to reflect its role as a shortcut key. How to accomplish that?


回答1:


Standard QAction widget (it is a QToolButton actually) uses stripped version of its text for display: "&Menu Option..." becomes "Menu Option".

You can create a custom QAction widget which does not use stripped text by subclassing QWidgetAction:

MyAction::MyAction(QObject *parent) :
    QWidgetAction(parent)
{
}

QWidget* MyAction::createWidget(QWidget *parent)
{
    QToolButton *tb = new QToolButton(parent);
    tb->setDefaultAction(this);
    tb->setText(this->text());// override text stripping
    tb->setFocusPolicy(Qt::NoFocus);

    return tb;
}

In your MainWindow constructor use it as follows:

MainWindow(QWidget* parent=0) : QMainWindow(parent)
{
    QToolBar* toolBar = new QToolBar(this);
    MyAction* action = new MyAction();
    action->setText("&Action");
    action->setShortcut(QKeySequence(tr("ctrl+a","Action")));
    toolBar->addAction(action);

    QObject::connect(action, SIGNAL(triggered()), this, SLOT(onAction()));
    addToolBar(toolBar);
}

Appearence of underline shortcut letters depends on your application style. Here is an example of a custom style that will force shortcut underline display:

class MyStyle : public QProxyStyle
{
public:
    MyStyle();

    int styleHint(StyleHint hint,
                  const QStyleOption *option,
                  const QWidget *widget,
                  QStyleHintReturn *returnData) const;
};

int MyStyle::styleHint(QStyle::StyleHint hint,
                   const QStyleOption *option,
                   const QWidget *widget,
                   QStyleHintReturn *returnData) const
{
    if (hint == QStyle::SH_UnderlineShortcut)
    {
        return 1;
    }

    return QProxyStyle::styleHint(hint, option, widget, returnData);
}

Then you should set that style to your application:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setStyle(new MyStyle);
    Widget w;
    w.show();

    return a.exec();
}


来源:https://stackoverflow.com/questions/32577789/qttoolbar-with-underlined-shortcut-key-in-button-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!