I want to display a single word in a QListWidgetItem in bold font. According to this related post, it should be possible to use QtCore.Qt.UserRole
for this purpose. However, the sample code provided did not work for me. (Since I'm a beginner, I most likely forgot a definition, but I don't know which one.)
This is what I have so far:
main.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>341</width>
<height>244</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QWidget" name="verticalLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>321</width>
<height>231</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListWidget" name="lwOptions"/>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
test.py
import os
import sys
from PyQt5 import QtCore, uic
from PyQt5.Qt import QApplication, QDialog, QListWidgetItem
class GUI(QDialog):
def __init__(self):
super(GUI, self).__init__()
dirname = os.path.dirname(os.path.abspath(__file__))
uic.loadUi(os.path.join(dirname,'main.ui'), self)
# this doesn't work
for ordinal in ['first', 'second', 'third']:
item = QListWidgetItem()
item.setData(QtCore.Qt.UserRole, 'This is the <b>{}</b> word.'.format(ordinal))
self.lwOptions.addItem(item)
for ordinal in ['fourth', 'fifth', 'sixth']:
item = QListWidgetItem('This is the <b>{}</b> word.'.format(ordinal))
self.lwOptions.addItem(item)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = GUI()
window.show()
sys.exit(app.exec_())
When I run the the code it'll add three empty lines and three lines with the verbatim messages.
What's the correct QtCore.Qt.UserRole
syntax?