I want to build a dropdown list control with QPushButton and QMenu like below:
QPushButton* menuBt = new QPushButton("Please select");
menuBt->setFlat(true);
QMenu* menu = new QMenu();
menuBt->setMenu(menu);
QWidgetAction* wa1 = new QWidgetAction(menu);
QLabel* l1 = new QLabel("Option1");
wa1->setDefaultWidget(l1);
menu->addAction(wa1);
QWidgetAction* wa2 = new QWidgetAction(menu);
QLabel* l2 = new QLabel("Option2");
wa2->setDefaultWidget(l2);
menu->addAction(wa2);
menu->setStyleSheet("QMenu::item {font-family: "Arial"; font-size: 13pt; color: #808080; border: 1px solid gray; background-color: rgb(234,234,234);}"
"QMenu::item:hover {background-color: rgb(0, 0, 255);}");
menuBt->setStyleSheet("QPushButton {font-family: "Arial"; font-size: 13pt; color: #808080; border: 1px solid gray;padding: 1px 18px 1px 3px;min-width: 6em; background-color: rgb(234,234,234);}");
I set the font and hover background color to the menu items by setStyleSheet, but seems it doesn't work.
How make the font and hover background color work on menu items?
Answer:
class QTDropDownButton : public QPushButton
{
Q_OBJECT
public:
QTDropDownButton(QString text, QWidget *parent = nullptr);
void addItem(QString text);
protected slots:
void menuAboutToShow();
private:
QMenu* menu_;
};
QTDropDownButton::QTDropDownButton(QString text, QWidget *parent) :
QPushButton(text, parent)
{
setFlat(true);
menu_ = new QMenu();
setMenu(menu_);
connect(menu_, SIGNAL(aboutToShow()), this, SLOT(menuAboutToShow()));
setStyleSheet("font-family: Arial; font-size: 13pt; color: #808080; border: 1px solid gray; background-color: rgb(234,234,234);");
menu_->setStyleSheet("QMenu::item {font-family: Arial; font-size: 13pt; color: #808080; border: 1px solid gray; background-color: rgb(234,234,234);}"
"QMenu::item:selected {background-color: rgb(0, 255, 255);}"
"QLabel {font-family: Arial; font-size: 13pt;}"
"QLabel:hover {background-color: rgb(0, 0, 255);}");
}
void QTDropDownButton::addItem(QString text)
{
if(!menu_)
return;
QWidgetAction* wa1 = new QWidgetAction(menu_);
QLabel* l1 = new QLabel(text);
wa1->setDefaultWidget(l1);
menu_->addAction(wa1);
}
void QTDropDownButton::menuAboutToShow()
{
if(menu_)
menu_->setFixedWidth(this->width());
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…