我想知道如何在样式表中访问并设置显示带有一堆 QToolButtons 的 QToolBar 时出现的“溢出按钮”的样式,因为并非所有按钮都适合窗口。
示例:
最佳答案
那个“按钮”是一个QToolBarExtension
,因此您可以使用该类名在 QSS 中选择它。
示例:
QToolBarExtension {
background-color: black;
}
结果如下:
在 QSS 中选择对象的另一个方法是通过其对象名称。因此 QToolBarExtension#qt_toolbar_ext_button
也可以工作。
由于 Qt 似乎没有提供一种根据扩展按钮的方向来设计扩展按钮样式的直接方法,因此我将尝试提供一种解决方法来解决您的问题。
继承QToolBar创建一个工具栏,当方向改变时更新扩展按钮名称。
mytoolbar.h
#ifndef MYTOOLBAR_H
#define MYTOOLBAR_H
#include <QToolBar>
class MyToolBar : public QToolBar
{
Q_OBJECT
public:
explicit MyToolBar(QWidget *parent = 0);
signals:
private slots:
void updateOrientation(Qt::Orientation orientation);
private:
QObject *extButton;
};
#endif // MYTOOLBAR_H
mytoolbar.cpp
#include "mytoolbar.h"
MyToolBar::MyToolBar(QWidget *parent) :
QToolBar(parent),
extButton(0)
{
// Obtain a pointer to the extension button
QObjectList l = children();
for (int i = 0; i < l.count(); i++) {
if (l.at(i)->objectName() == "qt_toolbar_ext_button") {
extButton = l.at(i);
break;
}
}
// Update extension nutton object name according to current orientation
updateOrientation(orientation());
// Connect orientationChanged signal to get the name updated every time orientation changes
connect (this, SIGNAL(orientationChanged(Qt::Orientation )),
this, SLOT(updateOrientation(Qt::Orientation)));
}
void MyToolBar::updateOrientation(Qt::Orientation orientation) {
if (extButton == 0)
return;
if (orientation == Qt::Horizontal)
extButton->setObjectName("qt_toolbar_ext_button_hor"); // Name of ext button when the toolbar is oriented horizontally.
else
extButton->setObjectName("qt_toolbar_ext_button_ver"); // Name of ext button when the toolbar is oriented vertically.
setStyleSheet(styleSheet()); // Update stylesheet
}
现在您可以这样设置按钮的样式:
QToolBarExtension#qt_toolbar_ext_button_hor {
background-color: black;
}
QToolBarExtension#qt_toolbar_ext_button_ver {
background-color: red;
}
其中,qt_toolbar_ext_button_hor
表示工具栏水平方向时的按钮,而 qt_toolbar_ext_button_ver
表示工具栏垂直方向时的按钮。
关于qt 如何设置 QToolBar > QToolButton 溢出按钮的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715698/