开发者

How to display icon in QDockWidget title bar?

My QDockWidget开发者_开发百科 has window title and close button. How do I put icon in title bar?

When I select icon from my recources for QDockWidget WindowIcon property, it's not working either.

Any ideas?


Through custom proxy-style:

class iconned_dock_style: public QProxyStyle{
    Q_OBJECT
    QIcon icon_;
public:
    iconned_dock_style(const QIcon& icon,  QStyle* style = 0)
        : QProxyStyle(style)
        , icon_(icon)
    {}

    virtual ~iconned_dock_style()
    {}

    virtual void drawControl(ControlElement element, const QStyleOption* option,
        QPainter* painter, const QWidget* widget = 0) const
    {
        if(element == QStyle::CE_DockWidgetTitle)
        {
            //width of the icon
            int width = pixelMetric(QStyle::PM_ToolBarIconSize);
            //margin of title from frame
            int margin = baseStyle()->pixelMetric(QStyle::PM_DockWidgetTitleMargin);

            QPoint icon_point(margin + option->rect.left(), margin + option->rect.center().y() - width/2);

            painter->drawPixmap(icon_point, icon_.pixmap(width, width));

            const_cast<QStyleOption*>(option)->rect = option->rect.adjusted(width, 0, 0, 0);
        }
        baseStyle()->drawControl(element, option, painter, widget);
    }
};

example:

QDockWidget* w("my title", paretn);
w->setStyle(new iconned_dock_style( QIcon(":/icons/icons/utilities-terminal.png"), w->style()));


thanks to @Owen, but I'd like add a few notes, for Qt 5.7:

1.QWidget::setStyle() doesn't take owership of the style object, so you need delete it after using it, or it will cause a resource leak.

2.for QProxyStyle(QStyle*), QProxyStyle will take ownership of the input style, but w->style() may return QApplication's style object if its custom style not set. so

new iconned_dock_style( QIcon(":/icons/icons/utilities-terminal.png"), w->style())

may take ownership of the app's style object, and on destruction, it will delete it. this will crash the app on QApplicatoin' shutdown time.

so now I use

new iconned_dock_style( QIcon(":/icons/icons/utilities-terminal.png"), NULL)


I think you can use QDockWidget::setTitleBarWidget(QWidget *widget).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜