qt 如何设置 QToolBar > QToolButton 溢出按钮的样式?

标签 qt qtstylesheets

我想知道如何在样式表中访问并设置显示带有一堆 QToolButtons 的 QToolBar 时出现的“溢出按钮”的样式,因为并非所有按钮都适合窗口。

示例:

example 1

example 2

最佳答案

那个“按钮”是一个QToolBarExtension,因此您可以使用该类名在 QSS 中选择它。

示例:

QToolBarExtension {
    background-color: black;
}

结果如下:

enter image description here

在 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/

相关文章:

c++ - 左填充在 QListWidget 中不起作用

c++ - Qt 退出应用程序并显示另一个窗口

c++ - 上下文菜单适用于子组件但不适用于父组件

c++ - QextSerialPort 的字符编码问题 (Qt/C++)

c++ - QT内容大小超过窗口大小时不出现滚动条

qt - 下拉列表中所选项目的 QComboBox 样式

c++ - Qt中如何设置menu::item::selected的样式?

python - 如何在不影响滚动条颜色的情况下更改 QScrollArea 的背景颜色?

qt - 使用 QApplication::setStyleSheet 覆盖 Qt 中设置的 QSS 属性

c++ - Qt 5 样式 : dynamically load qml files