c++ - 根据窗口大小动态更改 QToolButtons 的 ToolButtonStyle
问题描述
我创建了一个小部件类 (in C++
) ToolTray
,它基本上QToolButton
是在QHboxLayout
. 用户使用这些按钮进行诸如 等操作Save
。Open
最初,这些按钮被添加为toolButtonStyle
设置为Qt::ToolButtonTextBesideIcon
。
如果新大小toolButtonStyle
不足以显示Qt::ToolButtonIconOnly
. 见下图:resizeEvent
QToolButton
如果窗口被调整大小并且新的大小足以显示所有 QToolButton 的文本和图标,那么toolButtonStyle
应该改回Qt::ToolButtonTextBesideIcon
.
我试图用下面的代码来实现这一点:
void ToolTray::resizeEvent(QResizeEvent *event)
{
int totalWidth = 0;
bool mode = runBtn_->toolButtonStyle() == Qt::ToolButtonStyle::ToolButtonIconOnly;
// Mode => True => For ICON Only
// Mode => False => For ICON + Text
for (auto btn: toolBtns_) {
if (btn->isVisible())
totalWidth += btn->size().width();
}
qDebug() << "Total Width: " << totalWidth ;
qDebug() << "Event Size: " << event->size() << " Old size " << event->oldSize();
if (event->oldSize().isEmpty()) // Ignore ResizeEvent for QSize(-1,-1)
return;
if (mode) { // Already Small
if (event->size().width() < preferedFullWidth_)
return;
for (auto btn: toolBtns_) {
if (btn == moreBtn_)
continue;
btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
}
return;
}
// The QToolButtons are Text Beside Icon
if (event->size().width() >= totalWidth)
return;
qDebug() << "Here";
for (auto btn: toolBtns_)
btn->setToolButtonStyle(Qt::ToolButtonIconOnly);
preferedFullWidth_ = totalWidth;
}
但是,我无法实现我想要的:
每当我尝试缩小窗口的大小时,QToolButton 的 Text 首先开始剪辑,然后再缩小一些尺寸后,将
ToolButtonStyle
其更改为Qt::ToolButtonIconOnly
. 我不希望剪辑发生。我还想在我的实现中添加一些边距(或滞后)。就像一旦将 QToolButton 更改为
Qt::ToolButtonIconOnly
特定宽度,那么宽度应该大于preferedFullWidth_ + 一定的边距才能切换回Qt::ToolButtonTextBesideIcon
.
解决方案
工具栏似乎是本周的主题...... :)
所以你基本上有正确的想法,但棘手的部分是弄清楚所需的大小。不幸的是,QToolBar
布局是完全私有的,所以我们必须自己解决问题(即使它继承自QLayout
你无法通过 获取它的实例QToolBar::layout()
)。
这个实现是相当基本的,可能无法处理所有情况(我只测试了基本操作,没有自定义小部件等),但它确实适用(在 Windows 和 Linux 上以各种样式进行测试)。
补充:我意识到你并没有特别要求 a QToolBar
,但这就是你所描述的......我不确定为什么要重新发明那个轮子(aQToolBar
可以放在任何布局中,不必在 a主窗口),但是如果您要实现自己的版本,我认为这个示例的很多内容仍然适用。我个人也几乎总是使用QAction
s 来触发 UI 事件(相对于按钮),因为它们可以分配给任意数量的 UI 元素(工具栏、菜单栏、上下文菜单、窗口快捷方式等)。
添加边距/滞后作为练习留给读者...... :) 我认为它不需要,但你可以 m_expandedSize
用initSizes()
一些任意边距填充。
折叠工具栏
#include <QtWidgets>
class CollapsingToolBar : public QToolBar
{
Q_OBJECT
public:
explicit CollapsingToolBar(QWidget *parent = nullptr) : CollapsingToolBar(QString(), parent) {}
explicit CollapsingToolBar(const QString &title, QWidget *parent = nullptr) :
QToolBar(title, parent)
{
initSizes();
// If icon sizes change we need to recalculate all the size hints, but we need to wait until the buttons have adjusted themselves, so we queue the update.
connect(this, &QToolBar::iconSizeChanged, [this](const QSize &) {
QMetaObject::invokeMethod(this, "recalcExpandedSize", Qt::QueuedConnection);
});
// The drag handle can mess up our sizing, update preferred size if it changes.
connect(this, &QToolBar::movableChanged, [this](bool movable) {
const int handleSz = style()->pixelMetric(QStyle::PM_ToolBarHandleExtent, nullptr, this);;
m_expandedSize = (movable ? m_expandedSize + handleSz : m_expandedSize - handleSz);
adjustForSize();
});
}
protected:
// Monitor action events to keep track of required size.
void actionEvent(QActionEvent *e) override
{
QToolBar::actionEvent(e);
int width = 0;
switch (e->type())
{
case QEvent::ActionAdded:
// Personal pet-peeve... optionally set buttons with menus to have instant popups instead of splits with the main button doing nothing.
//if (QToolButton *tb = qobject_cast<QToolButton *>(widgetForAction(e->action())))
// tb->setPopupMode(QToolButton::InstantPopup);
//Q_FALLTHROUGH;
case QEvent::ActionChanged:
width = widthForAction(e->action());
if (width <= 0)
return;
if (e->type() == QEvent::ActionAdded || !m_actionWidths.contains(e->action()))
m_expandedSize += width + m_spacing;
else
m_expandedSize = m_expandedSize - m_actionWidths.value(e->action()) + width;
m_actionWidths.insert(e->action(), width);
break;
case QEvent::ActionRemoved:
if (!m_actionWidths.contains(e->action()))
break;
width = m_actionWidths.value(e->action());
m_expandedSize -= width + m_spacing;
m_actionWidths.remove(e->action());
break;
default:
return;
}
adjustForSize();
}
bool event(QEvent *e) override
{
// Watch for style change
if (e->type() == QEvent::StyleChange)
recalcExpandedSize();
return QToolBar::event(e);
}
void resizeEvent(QResizeEvent *e) override
{
adjustForSize();
QToolBar::resizeEvent(e);
}
private slots:
// Here we do the actual switching of tool button style based on available width.
void adjustForSize()
{
int availableWidth = contentsRect().width();
if (!isVisible() || m_expandedSize <= 0 || availableWidth <= 0)
return;
switch (toolButtonStyle()) {
case Qt::ToolButtonIconOnly:
if (availableWidth > m_expandedSize)
setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
break;
case Qt::ToolButtonTextBesideIcon:
if (availableWidth <= m_expandedSize)
setToolButtonStyle(Qt::ToolButtonIconOnly);
break;
default:
break;
}
}
// Loops over all previously-added actions and re-calculates new size (eg. after icon size change)
void recalcExpandedSize()
{
if (m_actionWidths.isEmpty())
return;
initSizes();
int width = 0;
QHash<QAction *, int>::iterator it = m_actionWidths.begin();
for ( ; it != m_actionWidths.end(); ++it) {
width = widthForAction(it.key());
if (width <= 0)
continue;
m_expandedSize += width + m_spacing;
it.value() = width;
}
adjustForSize();
}
private:
void initSizes()
{
// Preload some sizes based on style settings.
// This is the spacing between items
m_spacing = style()->pixelMetric(QStyle::PM_ToolBarItemSpacing, nullptr, this);
// Size of a separator
m_separatorWidth = style()->pixelMetric(QStyle::PM_ToolBarSeparatorExtent, nullptr, this);
// The layout margins (we can't even get the private QToolBarLayout via layout() so we figure it out like it does)
m_expandedSize = (style()->pixelMetric(QStyle::PM_ToolBarItemMargin, nullptr, this) + style()->pixelMetric(QStyle::PM_ToolBarFrameWidth, nullptr, this)) * 2;
// And the size of the drag handle if we have one
if (isMovable())
m_expandedSize += style()->pixelMetric(QStyle::PM_ToolBarHandleExtent, nullptr, this);
}
int widthForAction(QAction *action) const
{
// Try to find how wide the action representation (widget/separator) is.
if (action->isSeparator())
return m_separatorWidth;
if (QToolButton *tb = qobject_cast<QToolButton *>(widgetForAction(action))) {
const Qt::ToolButtonStyle oldStyle = tb->toolButtonStyle();
// force the widest size
tb->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
const int width = tb->sizeHint().width();
tb->setToolButtonStyle(oldStyle);
return width;
}
if (const QWidget *w = widgetForAction(action))
return w->sizeHint().width();
return 0;
}
int m_expandedSize = -1; // The maximum size we need with all buttons expanded and allowing for margins/etc
int m_spacing = 0; // Layout spacing between items
int m_separatorWidth = 0; // Width of separators
QHash<QAction *, int> m_actionWidths; // Use this to track action additions/removals/changes
};
测试/演示
// An XPM icon ripped from QCommonStyle
static const char * const info_xpm[]={
"32 32 5 1",
". c None",
"c c #000000",
"* c #999999",
"a c #ffffff",
"b c #0000ff",
"...........********.............",
"........***aaaaaaaa***..........",
"......**aaaaaaaaaaaaaa**........",
".....*aaaaaaaaaaaaaaaaaa*.......",
"....*aaaaaaaabbbbaaaaaaaac......",
"...*aaaaaaaabbbbbbaaaaaaaac.....",
"..*aaaaaaaaabbbbbbaaaaaaaaac....",
".*aaaaaaaaaaabbbbaaaaaaaaaaac...",
".*aaaaaaaaaaaaaaaaaaaaaaaaaac*..",
"*aaaaaaaaaaaaaaaaaaaaaaaaaaaac*.",
"*aaaaaaaaaabbbbbbbaaaaaaaaaaac*.",
"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
"*aaaaaaaaaaaabbbbbaaaaaaaaaaac**",
".*aaaaaaaaaaabbbbbaaaaaaaaaac***",
".*aaaaaaaaaaabbbbbaaaaaaaaaac***",
"..*aaaaaaaaaabbbbbaaaaaaaaac***.",
"...caaaaaaabbbbbbbbbaaaaaac****.",
"....caaaaaaaaaaaaaaaaaaaac****..",
".....caaaaaaaaaaaaaaaaaac****...",
"......ccaaaaaaaaaaaaaacc****....",
".......*cccaaaaaaaaccc*****.....",
"........***cccaaaac*******......",
"..........****caaac*****........",
".............*caaac**...........",
"...............caac**...........",
"................cac**...........",
".................cc**...........",
"..................***...........",
"...................**..........."};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
QToolBar* tb = new CollapsingToolBar(this);
tb->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
QIcon icon = QIcon(QPixmap(info_xpm));
for (int i=0; i < 6; ++i)
tb->addAction(icon, QStringLiteral("Action %1").arg(i));
addToolBar(tb);
show();
// Adding another action after show() may collapse all the actions if the new toolbar preferred width doesn't fit the window.
// Only an issue if the toolbar size hint was what determined the window width to begin with.
//tb->addAction(icon, QStringLiteral("Action After"));
// Test setting button style after showing (comment out the one above)
//tb->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
// Test changing icon size after showing.
//tb->setIconSize(QSize(48, 48));
// Try this too...
//tb->setMovable(false);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
//QApplication::setStyle("Fusion");
//QApplication::setStyle("windows");
MainWindow w;
return app.exec();
}
推荐阅读
- android - Android Seekbar 值在某些设备上不会为负数
- r - 对数据表进行排序后,我可以选择一个值,取消排序,然后将该值及其下方的 5 个值保存到数据框中吗?
- python-sphinx - Sphinx readthedocs 安装目录的布局与在我自己的机器上安装不同。如何使它们相同?
- python - Socket编程+Python中的HTTP1.1
- c# - 有没有办法在统一 3d 中拖放 UI 按钮?
- c++ - 带有继承的 C++ 模板的生成器模式
- c++ - 与作用域相关的局部变量定义,C++
- java - 无法从 java 程序访问数据
- data-structures - 用另一个数据结构初始化 Rust 中数据结构的字段
- python - 使用python数据类时出现TypeError