简体   繁体   中英

Qt: How to set “?” button for a QWidget?

In a QWidget like QLabel, how can we set a "?" button, such that when clicked (or hovered) it should show some help text.

Easiest way to show help when hover QWidget: setToolTip(QString) and setToolTipDuration(int). If you want a "?" button, just implement your own QWidget. Then via ui designer or directly in your code add QPushButton and QLabel on layout, and show your QLabel with help text in position of cursor when clicked(). Something like this:

{
// Constructor
...
    m_mainLabel = new QLabel("Main text");
    m_button = new QPushButton("?");
    m_helpLabel = new QLabel("Help text");
    connect(m_button, SIGNAL(clicked(bool)),
            this, SLOT(slotShowOrHideHelpLabel(bool)));
    QHBoxLayout *hBoxLayout = new QHBoxLayout;
    hBoxLayout->addWidget(m_mainLabel);
    hBoxLayout->addWidget(m_button);
    setLayout(hBoxLayout);
}

void slotShowOrHideHelpLabel(bool showHelpLabel)
{
    if (showHelpLabel)
    {
        m_helpLabel->show();
        m_helpLabel->move(QCursor::pos());
    }
    else
    {
        m_helpLabel->hide();
    }
}

Also you can use QMenu instead of QPushButton + QLabel.

// Constructor
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotCustomMenu(QPoint)));

// slotCustomMenu(QPoint)
QMenu menu(this);
menu.addAction(this->toolTip());
menu.addAction(this->whatsThis());
menu.exec(QCursor::pos());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM