繁体   English   中英

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

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

在QLabel这样的QWidget中,我们如何设置“?” 按钮,以便在单击(或悬停)时应显示一些帮助文本。

悬停QWidget时显示帮助的最简单方法:setToolTip(QString)和setToolTipDuration(int)。 如果要一个“?” 按钮,只需实现自己的QWidget。 然后通过ui设计器或直接在您的代码中在布局上添加QPushButton和QLabel,并在clicked()时将QLabel和帮助文本显示在光标位置。 像这样:

{
// 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();
    }
}

您也可以使用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