簡體   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