我需要QMenu
中的文本右对齐而不是左对齐。
QMenu menu;
menu.setStyleSheet("QMenu{background: #2e353d; color: #bfbfbf; margin: 0px;}"
"QMenu::item{font-size: 10pt; padding: " + QString::number(6*globalDPI) + "px " + QString::number(30*globalDPI) + "px " + QString::number(6*globalDPI) + "px " + QString::number(20*globalDPI) + "px; border: 0px solid transparent; margin: 0px;}"
"QMenu::item:selected{background: #373f49; color: #fff;}");
menu.addAction("Debug Log");
menu.addAction("Website");
menu.addAction("Changelog");
menu.addAction("About");
menu.exec(myButton->mapToGlobal(QPoint(0,32*globalDPI)));
我已经尝试在样式表的text-align: right
和QMenu
中同时添加QMenu::item
。我尝试使用setLayoutDirection
将布局方向设置为从右到左。我尝试将subcontrol-position: right;
添加到样式表中。无效,菜单中的文本保持左对齐。
有什么想法吗?
#include <QtWidgets>
class MenuProxyStyle: 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){
if(const QStyleOptionMenuItem *o = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)){
QStyleOptionMenuItem menuitem = *o;
QString text = o->text;
menuitem.text = "";
QProxyStyle::drawControl(element, &menuitem, p, w);
if(o->text.isEmpty())
return;
int margin = 4;
int text_flags = Qt::AlignVCenter | Qt::AlignRight | Qt::TextDontClip | Qt::TextSingleLine;
p->drawText(menuitem.rect.adjusted(margin, margin, -margin, -margin), text_flags, text);
return;
}
}
QProxyStyle::drawControl(element, opt, p, w);
}
};
class Widget: public QWidget{
public:
Widget(QWidget *parent=nullptr): QWidget(parent){
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, this, &Widget::on_customContextMenuRequested);
}
private:
void on_customContextMenuRequested(const QPoint &pos){
QMenu menu;
menu.setStyle(new MenuProxyStyle(menu.style()));
menu.addAction("Debug Log");
menu.addAction("Website");
menu.addAction("Changelog");
menu.addAction("About");
menu.exec(mapToGlobal(pos));
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
Widget w;
w.resize(640, 480);
w.show();
return app.exec();
}