[英]How to show a QToolTip on mouse press event and leave it popped up for some time? Qt
根據 Qt 文檔,看起來這個 function 有另一種方法:
void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecDisplayTime )
您應該能夠指定顯示工具提示的時間。
編輯:
好吧,看起來這個方法在 mousePress 事件中不能正常工作,所以這里有一個使用 QTimer 的替代方法:
將這些添加到您的 class 中:
MyConstructor(...params...)
, m_tooltipTimer(new QTimer(this)) // don't forget this line
{
connect(m_tooltipTimer, SIGNAL(timeout()), this, SLOT(updateTooltip()));
setAcceptedMouseButtons(Qt::AllButtons);
}
...
public slots:
void mousePressEvent(QMouseEvent *event) override;
void updateTooltip();
...
private:
QPoint m_tooltipPos;
qint64 m_tooltipTimerStart;
QTimer *m_tooltipTimer;
然后在 your.cpp 中實現這些
void ::mousePressEvent(QMouseEvent *event) {
m_tooltipTimer->start(200); // 5x per second, automatically resets timer if already started
m_tooltipTimerStart = QDateTime::currentMSecsSinceEpoch();
m_tooltipPos = event->globalPos();
event->accept();
}
void ::updateTooltip() {
auto howLongShown = QDateTime::currentMSecsSinceEpoch() - m_tooltipTimerStart; // startTime here is the moment of first showing of the tooltip
qDebug() << howLongShown;
if (howLongShown < 1000) { // 1 sec
QToolTip::showText(m_tooltipPos, tr("Test Tooltip")); // Replace this with your own
} else {
QToolTip::hideText();
m_tooltipTimer->stop();
}
}
感謝@Ian Burns 的回答,我設法創建了自己的方法:
void ::mousePressEvent(QMouseEvent*)
{
QTimer::singleShot(200, [this]()
{
QToolTip::showText(mapToGlobal({}),
tr("Symbol Linking\navailable only for Price"), this);
});
}
不知何故,如果我在 mousePressEvent 方法中顯示一個工具提示,它會在我松開鼠標按鈕后立即消失。 QTimer 延遲彈出調用並在合理的時間內保持彈出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.