如何使 QToolTip 消息持久化?
Posted
技术标签:
【中文标题】如何使 QToolTip 消息持久化?【英文标题】:How to make QToolTip message persistent? 【发布时间】:2017-06-09 17:31:55 【问题描述】:我想在单击按钮后使 qtooltip 消息持久化。我打算以后用qtimer自己隐藏它,但问题是当我将鼠标光标从按钮rect移开时,消息消失了,我想让它留在那里,直到后来我打电话给hideText()
from PyQt4 import QtGui, QtCore
from functools import partial
class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
layout = QtGui.QVBoxLayout()
btn = QtGui.QPushButton('Push Me')
layout.addWidget(btn)
self.setLayout(layout)
btn.clicked.connect(partial(self.showFloatingMessage,'This is a long message'))
def showFloatingMessage(self, message='', delay=500):
desktop = QtGui.QApplication.desktop()
screen_num = desktop.screenNumber(QtGui.QCursor.pos())
screen_rect = desktop.screenGeometry(screen_num)
QtGui.QToolTip.showText(screen_rect.center(), message, None, screen_rect)
app = QtGui.QApplication([])
dialog = MyDialog()
dialog.show()
app.exec_()
【问题讨论】:
【参考方案1】:一个可能的解决方案是使用 QLabel 作为 QToolTip,我们通过启用 Qt.ToolTip 标志来做到这一点。在你的情况下:
from PyQt4 import QtGui, QtCore
class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
layout = QtGui.QVBoxLayout()
btn = QtGui.QPushButton('Push Me')
layout.addWidget(btn)
self.setLayout(layout)
btn.clicked.connect(lambda: self.showFloatingMessage('This is a long message', 5000))
def showFloatingMessage(self, message='', delay=500):
desktop = QtGui.QApplication.desktop()
screen_num = desktop.screenNumber(QtGui.QCursor.pos())
screen_rect = desktop.screenGeometry(screen_num)
lb = QtGui.QLabel(self)
lb.setWindowFlags(QtCore.Qt.ToolTip)
lb.setText(message)
lb.move(screen_rect.center())
lb.show()
QtCore.QTimer.singleShot(delay, lb.hide)
app = QtGui.QApplication([])
dialog = MyDialog()
dialog.show()
app.exec_()
【讨论】:
以上是关于如何使 QToolTip 消息持久化?的主要内容,如果未能解决你的问题,请参考以下文章
如何更改 qtablewidget 项的 qtooltip 的背景颜色?