I really want a single QLabel to have different colours for different parts of the string. Past questions have led me to the solution of using HTML4 rich text options within it, for example:
'<font color="red">I\'m red! </font><font color="blue">I\'m blue!</font>'
This solution works great visually when passed into QLabel.setText()
, but for some reason I'm finding that mouse tracking completely breaks within the widget once it uses rich text.
Here's the MRE, with a normal QLabel and empty background space as a control:
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QMouseEvent
from PyQt5.QtCore import Qt, QEvent
import sys
class testWindow(QMainWindow):
def __init__(self):
super(testWindow, self).__init__()
self.setWindowTitle('QLabel Test')
self.setMouseTracking(True)
self.resize(600, 200)
# label that displays coordinates picked up from mouseMoveEvent
self.coordLabel = QLabel(self)
self.coordLabel.setText('Mouse at:')
self.coordLabel.setStyleSheet('''QLabel {background-color:#088;}''')
self.coordLabel.setGeometry(0, 0, 200, 200)
self.coordLabel.setMouseTracking(True)
# label with multiple colours for different sections of the string
self.richTextLabel = QLabel(self)
self.richTextLabel.setText('<font color="red">I\'m red! </font><font color="blue">I\'m blue!</font>')
self.richTextLabel.setStyleSheet('''QLabel {background-color:#880;}''')
self.richTextLabel.setTextFormat(Qt.RichText) # text format is explicitly set to RichText
self.richTextLabel.setGeometry(400, 0, 200, 200)
self.richTextLabel.setMouseTracking(True)
# everything has mouse tracking set to True
# 3 blocks: coordinate label, empty space, rich text label
self.show()
def mouseMoveEvent(self, event: QMouseEvent) -> None:
if event.type() == QEvent.MouseMove:
x, y = event.x(), event.y() # coordinates of mouse
self.coordLabel.setText('Mouse at: {}, {}'.format(x, y)) # set to coordLabel text
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = testWindow()
sys.exit(app.exec_())
What I'm looking for is either a way to fix the mouse tracking on these QLabels. Although if there's another way to make a QLabel with multiple colours in one string of text that would be helpful too.
Thanks :)