Remove icon space from QMenu

非 Y 不嫁゛ 提交于 2020-05-08 03:17:07

问题


I'm working on a Qt application (in C++). Without appyling any styles, my menu looks like this:

I'd like it to look like this:

How do I achieve this? Either using qss, or programmatically?

I already tried this, without success:

    menu->addAction(tr("Add"), this, SLOT(CreateNewWaypoint()))->setIconVisibleInMenu(false);

Answers for both Qt4.8 and Qt5 are needed to get the full bounty!


回答1:


One way to solve the problem is to use QProxyStyle:

customstyle.h

#ifndef CUSTOMSTYLE_H
#define CUSTOMSTYLE_H
#include <QProxyStyle>
#include <QStyleOptionMenuItem>

class CustomStyle : public QProxyStyle{
public:
    using QProxyStyle::QProxyStyle;

    void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *w) const override
    {
        if(element == QStyle::CE_MenuItem){
            QStyleOptionMenuItem myMenuOption;
            const QStyleOptionMenuItem *menuOption =
                    qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
            if (menuOption) {
                const int width = pixelMetric(PM_SmallIconSize)+6;
                myMenuOption = *menuOption;
                QRect r(myMenuOption.rect);
                r.setLeft(-width);
                myMenuOption.rect = r;
            }
            QProxyStyle::drawControl(element, &myMenuOption, p, w);
            return;
        }
        QProxyStyle::drawControl(element, opt, p, w);
    }
};

#endif // CUSTOMSTYLE_H

then you install it in the QApplication:

QApplication a(argc, argv);
QApplication::setStyle(new CustomStyle);



回答2:


You can influence on how your menu appears by playing with its style sheet. With you example code you can do the following:

menu.setStyleSheet("QMenu::item {"
                   "padding: 2px 5px 2px 2px;"
                   "}"
                   "QMenu::item:selected {"
                   "background-color: rgb(0, 85, 127);"
                   "color: rgb(255, 255, 255);"
                   "}");

Note the padding property, which sets the offsets of your menu item rectangles.



来源:https://stackoverflow.com/questions/44745459/remove-icon-space-from-qmenu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!