Qt dropdown menu with text under the button

119 Views Asked by At

I am working on a drop-down menu with C++ Qt4.8. This is the repo I used for testing Qt-Ribbon-Widget. The current menu contains rows of icon in the left, and text in the right.

text in the right of the icon

I want to make the icon as same size as the menu button, and with the text under the icon. here is my drawing.

text under the icon

This is the code for the adding menu to the button

  // Create 'Open file' button
  QToolButton *openFileButton = new QToolButton(this);
  openFileButton->setText(tr("File"));
  openFileButton->setToolTip(tr("Open file or directory"));
  openFileButton->setIcon(QIcon(":/icons/add_folder_2.svg"));

  // Create dropdown menu
  openFileButton->setPopupMode(QToolButton::MenuButtonPopup);
  QMenu *menu = new RibbonIconMenu("Title");
  menu->addAction(QIcon(":/icons/file_2.svg"), "Recent file 1");
  menu->addAction(QIcon(":/icons/file_2.svg"), "Recent file 2");
  menu->addAction(QIcon(":/icons/file_2.svg"), "Recent file 3");

  // Add this menu to the 'Open file' button
  openFileButton->setMenu(menu);

  ui->ribbonTabWidget->addButton("Project", openFileButton);

the icon and the text are pass separately in the addAction()

And this is the code for the custom menu, which is derived from QMenu.

#include <QMenu>
#include <QObject>

class RibbonIconMenu : public QMenu
{
    Q_OBJECT
public:
    RibbonIconMenu(const QString sName, QWidget *parent = nullptr);
};

RibbonIconMenu::RibbonIconMenu(const QString sName, QWidget *parent)
    : QMenu(sName, parent)
{

    // Set stylesheet
    QString styleSheetText = QString(
          // maybe?
        );

    setStyleSheet(styleSheetText);
}

According to Qt Documentation - The Style Sheet Syntax, "Qt Style Sheet terminology and syntactic rules are almost identical to those of HTML CSS.". I'm not familiar with HTML/CSS, but I found some HTML/CSS solution is using the HTML way. I wonder if there's CSS property type or some Qt's way to solve it?

update: I use QWidgetAction and solve it. See How to put pushbutton inside the QMenu or QAction control?.

for(int i = 0; i < 3; i++)
{
    QToolButton *openDatabaseButton = new QToolButton;
    openDatabaseButton->setText(tr("Database"));
    openDatabaseButton->setToolTip(tr("Connect to database"));
    openDatabaseButton->setIcon(QIcon(":/icons/add_database_2.svg"));
    openDatabaseButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    openDatabaseButton->setMinimumSize(48, 48);
    openDatabaseButton->setAutoRaise(true);
    openDatabaseButton->setIconSize(QSize(32,32));
    openDatabaseButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    QWidgetAction *toolButtonAction = new QWidgetAction(menu);
    toolButtonAction->setDefaultWidget(openDatabaseButton);
    menu->addAction(toolButtonAction);
}
openFileButton->setMenu(menu);
0

There are 0 best solutions below