简体   繁体   English

Qt:如何为QWidget设置“?”按钮?

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

In a QWidget like QLabel, how can we set a "?" 在QLabel这样的QWidget中,我们如何设置“?” 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). 悬停QWidget时显示帮助的最简单方法:setToolTip(QString)和setToolTipDuration(int)。 If you want a "?" 如果要一个“?” button, just implement your own QWidget. 按钮,只需实现自己的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(). 然后通过ui设计器或直接在您的代码中在布局上添加QPushButton和QLabel,并在clicked()时将QLabel和帮助文本显示在光标位置。 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. 您也可以使用QMenu代替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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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