Setting stylesheet to QMenu makes the section text disappear
-
I want to style a QMenu using a style sheet. For that, I have created a small example:
#include <QApplication> #include <QContextMenuEvent> #include <QMenu> #include <QWidget> class CustomWidget : public QWidget { Q_OBJECT public: CustomWidget(QWidget* parent = nullptr) : QWidget(parent) { setContextMenuPolicy(Qt::DefaultContextMenu); } virtual QSize sizeHint() const override { return QSize(150, 100); } protected: virtual void contextMenuEvent(QContextMenuEvent* event) override { // Create menu QMenu menu(this); menu.setStyleSheet("QMenu {" "background-color: #ABABAB;" "border: 1px solid black;" "}" "QMenu::item {" "background-color: transparent;" "}" "QMenu::item:selected {" "background-color: #654321;" "}"); menu.addAction(new QAction("Action 1", this)); menu.addSection("Section"); menu.addAction(new QAction("Action 2", this)); menu.exec(event->globalPos()); } }; int main(int argc, char** argv) { QApplication app(argc, argv); CustomWidget w; w.show(); return app.exec(); } #include "test_style.moc"
Where I set the style sheet as explained in the tutorial. The result of the menu is:
It can be seen in the image that the text of the
QMenu::addSection
is not displayed. Obviously, if I don't set the style sheet, the text is there:My experience is that when things like this happen is normally that you are missing something on the style sheet, but I have not been able to find which one is missing (I've tried the entire list in the already mentioned tutorial). Moreover, I've tried using the
"QMenu::separator"
without success:// Create menu QMenu menu(this); menu.setStyleSheet("QMenu {" "background-color: #ABABAB;" "border: 1px solid black;" "}" "QMenu::separator{" "height:1px;" "background:blue;" "margin-left:5px;" "margin-right:5px;" "}" "QMenu::item {" "background-color: transparent;" "}" "QMenu::item:selected {" "background-color: #654321;" "}"); menu.addAction(new QAction("Action 1", this)); menu.addSection("Section"); menu.addAction(new QAction("Action 2", this)); menu.exec(event->globalPos());
Does anybody have an idea on how to use the style sheet in a way that the section text is still displayed?
-
Hi,
What version of Qt are you running ?
-
QStyleSheetStyle does not support text in separators.
-
I guess then, that if I want the menus to follow my style and still show the text I should reimplement the drawControl function of the style? For the type QStyle::CE_MenuItem I guess? If i do this, i suppose I have to remove everything from the stylesheet to avoid anything being drawn using the QStyleSheetStyle::drawControl function?
-
@apalomer
Hi
Yes, you can use a QProxyStyle and overwrite drawControl
as it seems it is indeed used
https://code.woboq.org/qt5/qtbase/src/widgets/widgets/qmenu.cpp.html line 2794style()->drawControl(QStyle::CE_MenuItem, &opt, &p, this);