问题
I want to make a qtooltip message persistent after I clicked the button. I plan to use qtimer to hide it by myself later, but the problem is as soon as I move mouse cursor away from the button rect, the message disappears, I want to make it stay there, until later I call 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:
A possible solution is to use a QLabel as QToolTip, we do this by enabling the Qt.ToolTip flag. In your case:
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_()
来源:https://stackoverflow.com/questions/44463700/how-to-make-qtooltip-message-persistent