问题描述
我有一个带有纯文本按钮的简单 Qt 工具栏 Action
:
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);
}
我想让 Action
中的 A
加下划线以反映其作为快捷键的作用.如何做到这一点?
I would like to have A
in Action
underlined to reflect its role as a shortcut key. How to accomplish that?
推荐答案
Standard QAction
小部件(它实际上是一个 QToolButton
)使用其文本的剥离版本进行显示:&Menu Option..."变成Menu Option".
Standard QAction
widget (it is a QToolButton
actually) uses stripped version of its text for display: "&Menu Option..." becomes "Menu Option".
您可以通过子类化 QWidgetAction
来创建不使用剥离文本的自定义 QAction
小部件:
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;
}
在您的 MainWindow
构造函数中使用它,如下所示:
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();
}
这篇关于QtToolBar 在按钮文本中带有带下划线的快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!