1

It crashes when I attempt to store data using QtCore.Qt.UserRole and setData: item.setData(QtCore.Qt.UserRole, data)

Interesting, that a very similar approach works in PyQt4 (I am actually porting a previously written PyQt4 code to PyQt5).

from PyQt5 import QtCore, QtGui, QtWidgets

table = QtWidgets.QTableWidget()
items = ['Item_01','Item_02','Item_03']
column_names = ['Column_01','Column_02','Column_03']

for row, header in enumerate(items):
    for col, column_name in enumerate(column_names):    
        item = QtWidgets.QTableWidgetItem(column_name)
        table.setItem(row, col, item)
        item.setData(QtCore.Qt.UserRole, column_name)  
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • What if to use as UserRole value "*just randomly generated from head*" ```QtCore.Qt.UserRole + 10``` ? – Max Go Feb 13 '17 at 21:59
  • Also because "Qt::UserRole it's 0x0100", what if do replace of QtCore.Qt.UserRole with integer "8", like ```item.setData(8, column_name)``` – Max Go Feb 13 '17 at 22:06
  • I cannot reproduce this - unless the code is to be taken literally, and you have failed to create a `QApplication`. – ekhumoro Feb 13 '17 at 23:12
  • I can't replicate it too. I am running a third party application built around PyQt5. All the plugins written for it earlier now need to be re-written to address the differences in PyQt5. It appears that using `QtCore.Qt.UserRole+integer` works fine. Thanks! – alphanumeric Feb 13 '17 at 23:45

1 Answers1

1

I had the same issue, and @ekhumoro kindly helped me out.

I used a model/view approach, and the QTableWidget inherits QTableView so it should work for you as well.

column0 = QtGui.QStandardItem()
column0.setData('Some Label',QtCore.Qt.DisplayRole)
column0.setEditable(False)

x = 123.456

column1 = QtGui.QStandardItem()
column1.setData(x,QtCore.Qt.DisplayRole)

data = [column0, column1]

row = 0 #Specify a row.

for index, element in enumerate(data):
    model.setItem(row,index,element)
    # Or in this case you might write: treeWidget.setItem(...)

The list of roles that can be used can be found here.

EDIT I think I missed the point where you specified userRole in which case just specify:

QtCore.Qt.UserRole+desired_role_number
Community
  • 1
  • 1
NineTails
  • 550
  • 4
  • 24