Tim*_*ann 4 qt tooltip qtoolbar
我已经QActions添加到QToolBarusing addAction().
我希望工具栏按钮工具提示显示快捷方式。例如复制(Ctrl+C)。当然,我可以静态设置
action->setTooltip(QString("%1 (%2)").arg(action.toolTip(), action->shortcut().toString(QKeySequence::NativeText)));
Run Code Online (Sandbox Code Playgroud)
然而,这非常麻烦,因为有很多操作,并且用户可以修改快捷方式,因此我必须跟踪并相应更新。如果我可以通过类似于http://doc.qt.io/qt-5/qtwidgets-widgets-tooltips-example.htmlQToolBar的子类来简单地修改工具提示行为,那就更好了。QToolBar
不幸的是,事情没那么简单。工具提示不是由其本身生成的QToolBar,而是显然是由QToolButton使用时在内部创建的addAction()。所以理想情况下我会注入我自己的QToolButton. 但这似乎是不可能的,因为工具按钮的实际实例化是在我无法访问的私有 QToolBarLayout 内完成的。
有什么想法如何解决这个问题吗?
我无法通过子类化QToolBar或任何相关的方式找到解决方案。因此我不得不覆盖QAction. 这就是最终的样子:
我编写了函数来添加/删除快捷方式信息,以便更改是可逆的(例如,如果行为应该是可切换的,则需要)。如果不需要移除,addShortcutToToolTip()可以稍微简化一下。
/* guesses a descriptive text from a text suited for a menu entry
This is equivalent to QActions internal qt_strippedText()
*/
static QString strippedActionText(QString s) {
s.remove( QString::fromLatin1("...") );
for (int i = 0; i < s.size(); ++i) {
if (s.at(i) == QLatin1Char('&'))
s.remove(i, 1);
}
return s.trimmed();
}
/* Adds possible shortcut information to the tooltip of the action.
This provides consistent behavior both with default and custom tooltips
when used in combination with removeShortcutToToolTip()
*/
void addShortcutToToolTip(QAction *action)
{
if (!action->shortcut().isEmpty()) {
QString tooltip = action->property("tooltipBackup").toString();
if (tooltip.isEmpty()) {
tooltip = action->toolTip();
if (tooltip != strippedActionText(action->text())) {
action->setProperty("tooltipBackup", action->toolTip()); // action uses a custom tooltip. Backup so that we can restore it later.
}
}
QColor shortcutTextColor = QApplication::palette().color(QPalette::ToolTipText);
QString shortCutTextColorName;
if (shortcutTextColor.value() == 0) {
shortCutTextColorName = "gray"; // special handling for black because lighter() does not work there [QTBUG-9343].
} else {
int factor = (shortcutTextColor.value() < 128) ? 150 : 50;
shortCutTextColorName = shortcutTextColor.lighter(factor).name();
}
action->setToolTip(QString("<p style='white-space:pre'>%1 <code style='color:%2; font-size:small'>%3</code></p>")
.arg(tooltip, shortCutTextColorName, action->shortcut().toString(QKeySequence::NativeText)));
}
}
/* Removes possible shortcut information from the tooltip of the action.
This provides consistent behavior both with default and custom tooltips
when used in combination with addShortcutToToolTip()
*/
void removeShortcutFromToolTip(QAction *action)
{
action->setToolTip(action->property("tooltipBackup").toString());
action->setProperty("tooltipBackup", QVariant());
}
Run Code Online (Sandbox Code Playgroud)