I’m trying to build a GUI to a movies database Using a PyQt5 QListWidget I can add a list of movie titles However what I’d like to do add the database ID as well so when the user clicks a movie title the ID can be used to retrieve info about that movie This post https://stackoverflow.com/a/62514685/1382667 suggest using UserRole to setData but I’m getting errors
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QLineEdit, QPushButton, QListWidget, QTabWidget, \
QGraphicsWidget, QListView
from PyQt5 import uic, QtCore, QtWidgets
import sys
import DB_con
def getMovies(sql):
cursor = DB_con.db_con()
cursor.execute(sql)
records = cursor.fetchall()
print(type(records))
## <class 'list'>
for row in records:
print(row.id, row.title)
# 1052 'Crocodile' Dundee II
# 614 10,000 BC
# 2468 10.0 Earthquake
# 1327 100 Girls
# 2224 12 Years a Slave
return records
class UI(QMainWindow):
def __init__(self):
super(UI, self).__init__()
# Load the ui file
uic.loadUi("Movies.ui", self)
# Define Widgets
self.movieListWidget = self.findChild(QListWidget, "MovieListWidget")
# Get Movies
movies = getMovies("SELECT TOP 5 id,title FROM movie ORDER by title")
print(type(self.movieListWidget))
# <class 'PyQt5.QtWidgets.QListWidget'>
for movie in movies:
print(movie.id, movie.title)
# 1052 'Crocodile' Dundee II
# Adding to listWidget
#
item = QtWidgets.QListWidgetItem()
item.setText(movie.title)
item.setData(QtCore.Qt.UserRole, movie[0])
self.movieListWidget.addItems(item) # ERROR
# Adding just Title works
# self.movieListWidget.addItem(movie[1])
# Show The App
self.show()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
app = QApplication(sys.argv)
UIWindow = UI()
app.exec_()
Error
TypeError: addItems(self, Iterable[str]): argument 1 has unexpected type 'QListWidgetItem'