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

dol*_*boy 3 qt qtstylesheets

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

例子:

例子1

例子2

mhc*_*rvo 6

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

例:

QToolBarExtension {
    background-color: black;
}
Run Code Online (Sandbox Code Playgroud)

结果将是:

在此处输入图片说明

在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
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以按以下方式设置按钮的样式:

QToolBarExtension#qt_toolbar_ext_button_hor {
background-color: black;
}

QToolBarExtension#qt_toolbar_ext_button_ver {
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

其中qt_toolbar_ext_button_hor,当工具栏水平放置和qt_toolbar_ext_button_ver垂直放置时,按钮表示按钮。