How to make QAbstractTableModel 's data checkable
I want to make each cell in the following code can be checked or unchecked by the user ,how to modify the code ?
according to the Qt documentation :Qt::CheckStateRole and set the Qt::ItemIsUserCheckable might be used ,so anyone can give a little sample ?
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyModel(QAbstractTableModel):
def __init__(self, parent=None):
super(MyModel, self).__init__(parent)
def rowCount(self, parent = QModelIndex()):
return 2
def columnCount(self,parent = QModelIndex()) :
return 3
def data(self,index, role = Qt.DisplayRole) :
if (role == Qt.DisplayRole):
return "Row{}, Column{}".format(index.row() + 1, index.column() +1)
return None
if __name__ == '__main__':
app =QApplication(sys.argv)
tableView=QTableView()
myModel = MyModel (None);
tableView.setModel( myModel );
tableView.show();
sys.exit(app.exec_())
Override the flags function in MyModel.
def flags(self, index)
return super(MyModel, self).flags(index)|QtCore.Qt.ItemIsUserCheckable
This says that the index in your model is checkable.
Then override the data function.
def data(self,index, role = Qt.DisplayRole) :
if (role == Qt.DisplayRole):
return "Row{}, Column{}".format(index.row() + 1, index.column() +1)
elif (role==Qt.CheckStateRole):
# read from your data and return Qt.Checked or Unchecked
return None
Finally, you need to implement the setData function.
def setData(self, index, value, role = Qt.EditRole):
if (role==Qt.CheckStateRole):
# Modify your data.
I have a Qtableview with a filter option using QLineEdit. It works ok except:
When i choose an index the filter doesn't look in the index.
Row 0 isn't visible
What i would like is to be able to export the filter results to another dataframe.
This is my code , i'm new at this son feel free to correct ;-)
import timeit
import pandas as pd
from PyQt5 import QtGui
from PyQt5.QtCore import Qt, QSortFilterProxyModel
class PandasTableModel(QtGui.QStandardItemModel):
def __init__(self, data, parent=None):
QtGui.QStandardItemModel.__init__(self, parent)
self._data = data
for col in data.columns:
data_col = [QtGui.QStandardItem("{}".format(x)) for x in data[col].values]
self.appendColumn(data_col)
return
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def headerData(self, x, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[x]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.index[x]
return None
class Datahandler():
def __init__(self):
pass
def Load_Master_Data(self,tableMasterData,inputFilter):
print('Start Load_Master_Data')
start = timeit.default_timer()
Datafile = pd.read_pickle('modules/ssh/downloads/productsmaster.pkl')
df = pd.DataFrame(Datafile)
# df= df.set_index('Master_key')
self.inputfilter = inputFilter
self.tableMasterData = tableMasterData
self.df = df
self.model = PandasTableModel(df)
self.proxy_model = QSortFilterProxyModel()
self.proxy_model.setFilterKeyColumn(-1) # Search all columns.
self.proxy_model.setSourceModel(self.model)
self.proxy_model.sort(0, Qt.AscendingOrder)
self.proxy_model.setFilterCaseSensitivity(False)
self.tableMasterData.setModel(self.proxy_model)
inputFilter.textChanged.connect(self.proxy_model.setFilterFixedString)
end = timeit.default_timer()
print("Process Time: ",end-start)
Cheers , Johnson
I have been trying to update a QTableViewModel when inserting a new object that represents a row. I did follow the advise of several question in SO, but I cannot get an example to work.
After debugging, I found that the call to self.endInsertRows() produces the crash.
This is a minimal example:
import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
class Wire:
def __init__(self, name, x, y, gmr, r):
self.name = name
self.x = x
self.y = y
self.r = r
self.gmr = gmr
class WiresCollection(QtCore.QAbstractTableModel):
def __init__(self, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.header = ['Name', 'R (Ohm/km)', 'GMR (m)']
self.index_prop = {0: 'name', 1: 'r', 2: 'gmr'}
self.wires = list()
def add(self, wire: Wire):
"""
Add wire
:param wire:
:return:
"""
row = len(self.wires)
self.beginInsertRows(QtCore.QModelIndex(), row, row)
self.wires.append(wire)
self.endInsertRows()
def delete(self, index):
"""
Delete wire
:param index:
:return:
"""
row = len(self.wires)
self.beginRemoveRows(QtCore.QModelIndex(), row, row)
self.wires.pop(index)
self.endRemoveRows()
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.wires)
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.header)
def parent(self, index=None):
return QtCore.QModelIndex()
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
val = getattr(self.wires[index.row()], self.index_prop(index.column()))
return str(val)
return None
def headerData(self, p_int, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.header[p_int]
def setData(self, index, value, role=QtCore.Qt.DisplayRole):
"""
Set data by simple editor (whatever text)
:param index:
:param value:
:param role:
"""
wire = self.wires[index.row()]
attr = self.index_prop[index.column()]
setattr(wire, attr, value)
class TowerBuilderGUI(QtWidgets.QDialog):
def __init__(self, parent=None):
"""
Constructor
Args:
parent:
"""
QtWidgets.QDialog.__init__(self, parent)
self.setWindowTitle('Tower builder')
# GUI objects
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.layout = QVBoxLayout(self)
self.wires_tableView = QTableView()
self.add_wire_pushButton = QPushButton()
self.add_wire_pushButton.setText('Add')
self.delete_wire_pushButton = QPushButton()
self.delete_wire_pushButton.setText('Delete')
self.layout.addWidget(self.wires_tableView)
self.layout.addWidget(self.add_wire_pushButton)
self.layout.addWidget(self.delete_wire_pushButton)
self.setLayout(self.layout)
# Model
self.wire_collection = WiresCollection(self)
# set models
self.wires_tableView.setModel(self.wire_collection)
# button clicks
self.add_wire_pushButton.clicked.connect(self.add_wire_to_collection)
self.delete_wire_pushButton.clicked.connect(self.delete_wire_from_collection)
def msg(self, text, title="Warning"):
"""
Message box
:param text: Text to display
:param title: Name of the window
"""
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText(text)
# msg.setInformativeText("This is additional information")
msg.setWindowTitle(title)
# msg.setDetailedText("The details are as follows:")
msg.setStandardButtons(QMessageBox.Ok)
retval = msg.exec_()
def add_wire_to_collection(self):
"""
Add new wire to collection
:return:
"""
name = 'Wire_' + str(len(self.wire_collection.wires) + 1)
wire = Wire(name, x=0, y=0, gmr=0, r=0.01)
self.wire_collection.add(wire)
def delete_wire_from_collection(self):
"""
Delete wire from the collection
:return:
"""
idx = self.ui.wires_tableView.currentIndex()
sel_idx = idx.row()
if sel_idx > -1:
self.wire_collection.delete(sel_idx)
else:
self.msg('Select a wire in the wires collection')
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = TowerBuilderGUI()
window.show()
sys.exit(app.exec_())
As indicated in the comments you have 2 errors:
The first is when you press add because when you add a new item you have to refresh the view and that's why it's called data() method and it's where the error is shown in self.index_prop(index.column()), index_pro is a dictionary so you should use [] instead of ().
val = getattr(self.wires[index.row()], self.index_prop[index.column()])
Another error is generated by the line idx = self.ui.wires_tableView.currentIndex(), the ui does not exist and it is not necessary, sure it is a remnant of a previous code, to access wires_tableView as this is a member of the class not it is necessary to use an intermediary, you must access directly with self: idx = self.wires_tableView.currentIndex()
The above are typos and probably mark it so that the question is closed there is another error that is not, and that is the reason for my answer.
In the line self.beginRemoveRows(...) you must pass the row that you are going to remove but you are passing the row that does not exist:
row = len(self.wires)
self.beginRemoveRows(QtCore.QModelIndex(), row, row) # <---- row does not exist in the table
The solution is simple, change it by index:
def delete(self, index):
"""
Delete wire
:param index:
:return:
"""
self.beginRemoveRows(QtCore.QModelIndex(), index, index)
self.wires.pop(index)
self.endRemoveRows()
After hanging around with some posts with C++ answers which don't fit to my question and which are more confusing than explaining I try to ask here.
I'm trying to subclass QSqlTableModel because I need some boolean columns with checkboxes. The complete working program is:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *
import sys
class ImportFilter (QDialog):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
print("Welcome to StandardDialog")
# Load the Window
#self.ui = uic.loadUi("ImportFilter.ui",self)
#self.ui.setModal(True)
self.buttonBox = QDialogButtonBox()
self.tableView_typeOfValues = QTableView()
layout = QVBoxLayout()
layout.addWidget(self.buttonBox)
layout.addWidget(self.tableView_typeOfValues)
self.setLayout(layout)
# Init Environmment
self.db = createConnection()
# create Models
self.setupModel()
#setup Views
self.setupView()
# connect Signals
self.buttonBox.clicked.connect(self.pushButton_Box_clicked)
self.show()
print("<- initUI")
def setupView(self):
print("-> setupView")
self.tableView_typeOfValues.setModel(self.tableView_typeOfValues_Model)
self.tableView_typeOfValues.setColumnWidth(0,10)
self.tableView_typeOfValues.setColumnWidth(1,130)
self.tableView_typeOfValues.setColumnWidth(2,130)
self.tableView_typeOfValues.setColumnWidth(3,60)
self.tableView_typeOfValues.setColumnWidth(4,60)
self.tableView_typeOfValues.setColumnWidth(5,60)
self.tableView_typeOfValues.setColumnWidth(6,60)
self.tableView_typeOfValues.hideColumn(0)
self.tableView_typeOfValues.hideColumn(3)
print("<- setupView")
def setupModel(self):
print("-> setupModel")
# own model
self.tableView_typeOfValues_Model = ImportSqlTableModel()
print(" tables:", self.db.tables())
print(' Before .setTable("typeOfValue") and select()')
self.tableView_typeOfValues_Model.info()
self.tableView_typeOfValues_Model.setTable("typeOfValue")
self.tableView_typeOfValues_Model.setEditStrategy(QSqlTableModel.OnFieldChange)
self.tableView_typeOfValues_Model.select()
print(' After .setTable("typeOfValue") and select()')
self.tableView_typeOfValues_Model.info()
self.headerData()
print(" Table:",self.tableView_typeOfValues_Model.tableName())
print(" count:",self.tableView_typeOfValues_Model.rowCount())
self.tableView_typeOfValues_Model.info()
print("<- setupModel")
def setupModelQRY(self):
print("-> setupModel with Query")
# works so far
#self.tableView_typeOfValues_Model = QSqlTableModel() # edit but no checkboxes
self.tableView_typeOfValues_Model = ImportSqlTableModel(self.db) # no edit
# SET query
qry = QSqlQuery(self.db)
sql = "SELECT ID, name, unit, source, Import, ImportIfZero, visible FROM typeOfValue"
qry.prepare(sql)
qry.exec_(sql)
self.tableView_typeOfValues_Model.setQuery(qry)
self.tableView_typeOfValues_Model.select()
print(" Filter:",self.tableView_typeOfValues_Model.filter())
print(" SELECT:", self.tableView_typeOfValues_Model.selectStatement())
self.tableView_typeOfValues_Model.setEditStrategy(QSqlTableModel.OnFieldChange)
print("<- setupModel")
def headerData(self):
print("-> headerData")
self.tableView_typeOfValues_Model.setHeaderData(0,Qt.Horizontal, "ID")
self.tableView_typeOfValues_Model.setHeaderData(1,Qt.Horizontal, "name")
self.tableView_typeOfValues_Model.setHeaderData(2,Qt.Horizontal, "unit")
self.tableView_typeOfValues_Model.setHeaderData(3,Qt.Horizontal, "source")
self.tableView_typeOfValues_Model.setHeaderData(4,Qt.Horizontal, "Import")
self.tableView_typeOfValues_Model.setHeaderData(5,Qt.Horizontal, "ImportIfZero")
self.tableView_typeOfValues_Model.setHeaderData(6,Qt.Horizontal, "visible")
print("<- headerData")
###################################################################################################
# functions
###################################################################################################
def pushButton_Box_clicked(self,signal):
print("okButtonClicked")
print("buttonBox_clicked",signal)
self.tableView_typeOfValues_Model.submitAll()
self.exitcode = "ok, but not implemented"
sys.exit()
def returnCode(self):
return self.exitcode
#######################################################################################################################
# C L A S S
#######################################################################################################################
class ImportSqlTableModel(QSqlTableModel):
def __init__(self):
super(ImportSqlTableModel, self).__init__()
print("-> ImportSqlTableModel.__init__:")
self.booleanSet =[4,5,6]
self.readOnlySet = [1]
print(" Inside:")
self.info()
print("<- ImportSqlTableModel.__init__:")
def info(self):
print("-> info")
print(" ImportSqlTableModel tables inside :", self.database().tables())
print(" ImportSqlTableModel self.db :", self.database())
print(" ImportSqlTableModel self.Table :", self.tableName())
print(" ImportSqlTableModel self.rowCount :", self.rowCount())
print(" ImportSqlTableModel self.lastEror :", self.lastError().text())
print("<- info")
def columnCount(self, index):
count = QSqlTableModel.columnCount(self, index)
return count
def dataChanged(self, QModelIndex, QModelIndex_1, Iterable, p_int=None, *args, **kwargs):
print("-> Datachanged")
def data(self, index, role=Qt.DisplayRole):
print("-> ImportSqlModel.data",index, role)
print(" 1row :", index.row())
print(" col :", index.column())
print(" data :", self.record().fieldName(index.column()))
value = super(ImportSqlTableModel, self).data(index)
print(" value2:",value)
if index.column() in self.booleanSet:
if role == Qt.CheckStateRole:
if value == 2:
return QVariant(Qt.Unchecked)
else:
return QVariant(Qt.Checked)
else:
QSqlTableModel.data(self, index, role)
else:
return QSqlTableModel.data(self, index, role)
def setData(self, index, value, role=Qt.EditRole):
# works with changing value, but not saving
print("-> ImportSqlModel.setData",index,value,role)
print(" value:", value)
if not index.isValid():
return False
if role == Qt.EditRole:
print(" = Qt.Editrole")
QVariant(value)
print(" Update table")
self.select()
if index.column() in self.booleanSet and role == Qt.CheckStateRole:
print(" checkbox changed!")
if value == Qt.Checked:
print(" Qt.Checked")
return QSqlTableModel.setData(self, index, 2 , Qt.EditRole)
else:
print(" not Qt.Checked")
return QSqlTableModel.setData(self, index, 0 , Qt.EditRole)
else:
return QSqlTableModel.setData(self, index, value, role)
def flags(self, index):
print("-> ImportSqlModel.flags")
print(" index.isValid()",index.isValid())
if not index.isValid():
return Qt.ItemIsEnabled
if index.column() in self.booleanSet:
return Qt.ItemIsUserCheckable | Qt.ItemIsEnabled # | Qt.ItemIsSelectable | Qt.ItemIsEditable
elif index.column() in self.readOnlySet:
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
else:
return QSqlTableModel.flags(self, index)
print("<- ImportSqlModel.flags")
#######################################################################################################################
# D E M O F U N C T I O N
#######################################################################################################################
def createConnection():
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('memory')
if not db.open():
QMessageBox.critical(None, qApp.tr("Cannot open database"),
qApp.tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information "
"how to build it.\n\n"
"Click Cancel to exit."),
QMessageBox.Cancel)
return False
query = QSqlQuery()
query.exec_("CREATE TABLE `typeOfValue` (`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, "\
"`name` TEXT NOT NULL, `unit` TEXT NOT NULL,`source` TEXT,`import` INTEGER,`importIfZero` INTEGER,"\
"`visible` INTEGER);")
query.exec_('insert into typeOfValue (name, unit, source, import, importIfZero, visible) values '\
'("Sound", "dB", "live", 0,0,2)')
query.exec_('insert into typeOfValue (name, unit, source, import, importIfZero, visible) values '\
'("Flow", "m/min", "live", 0,2,2)')
query.exec_('insert into typeOfValue (name, unit, source, import, importIfZero, visible) values '\
'("Vibration", "mm/s", "live", 2,2,2)')
query.exec_('insert into typeOfValue (name, unit, source, import, importIfZero, visible) values '\
'("Voltage", "V", "live", 0,0,0)')
query.exec_('insert into typeOfValue (name, unit, source, import, importIfZero, visible) values '\
'("Ampere", "A", "live", 2,0,2)')
return db
#######################################################################################################################
# M A I N
#######################################################################################################################
if __name__ == '__main__':
createConnection()
app = QApplication(sys.argv)
prog = ImportFilter()
prog.show()
sys.exit(app.exec_())
The problem I was running in, is that I am able to view the table when I use a query to fill it:
def setupModel(self):
print("-> setupModel")
# SET query
qry = QSqlQuery(self.gVar.db)
sql = "SELECT ID, name, unit, source, Import, ImportIfZero, visible FROM typeOfValue"
qry.prepare(sql)
qry.exec_(sql)
self.tableView_typeOfValues_Model.setQuery(qry)
But I found the fault, that this leads to read-only tables. It is described in the manual that it should not be done: See here
So I changed to .setTable("typeOfValue") # = Tablename
self.tableView_typeOfValues_Model = ImportSqlTableModel(self.gVar.db)
self.tableView_typeOfValues_Model.setTable("typeOfValue")
self.tableView_typeOfValues_Model.setEditStrategy(QSqlTableModel.OnFieldChange)
self.tableView_typeOfValues_Model.select()
But now I have an empty view and if I call self.lastError().text() I got the message that the table will not be found because self.database().tables() (called inside the model) brings an empty list. That means to me, that the database is not initialized correctly, but self.database() brings
PyQt5.QtSql.QSqlDatabase object at 0x042C4D30 as result.
Please, can someone give me the hint to correct subclassing QSqlTableModel. Thanks!
The problem is caused by the Qt.ItemIsEditable flag that is not enabled for the Boolean type column, this is necessary in the instruction:
if index.column() in self.booleanSet and role == Qt.CheckStateRole:
print(" checkbox changed!")
if value == Qt.Checked:
print(" Qt.Checked")
return QSqlTableModel.setData(self, index, 2 , Qt.EditRole)
else:
print(" not Qt.Checked")
return QSqlTableModel.setData(self, index, 0 , Qt.EditRole)
since it verifies that the field can be edited.
So the solution is to enable this flag, but to avoid that you can write some text we will disable the Editor through a delegate:
class ReadOnlyDelegate(QItemDelegate):
def createEditor(self, parent, option, index):
lb = QLabel(parent)
return lb
Complete Example:
import sys
from PyQt5.QtCore import QVariant, Qt
from PyQt5.QtSql import QSqlTableModel, QSqlDatabase
from PyQt5.QtWidgets import QApplication, QTableView, QLabel, QItemDelegate
class ImportSqlTableModel(QSqlTableModel):
def __init__(self, *args, **kwargs):
super(ImportSqlTableModel, self).__init__(*args, **kwargs)
self.booleanSet = [4, 5, 6] # column with checkboxes
self.readOnlySet = [1] # columns which must not be changed
self.setTable("typeOfValue")
self.setEditStrategy(QSqlTableModel.OnFieldChange)
self.select()
def data(self, index, role=Qt.DisplayRole):
value = super(ImportSqlTableModel, self).data(index)
if index.column() in self.booleanSet:
if role == Qt.CheckStateRole:
return Qt.Unchecked if value == 2 else Qt.Checked
else:
return QVariant()
return QSqlTableModel.data(self, index, role)
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid():
return False
if index.column() in self.booleanSet:
if role == Qt.CheckStateRole:
val = 2 if value == Qt.Unchecked else 0
return QSqlTableModel.setData(self, index, val, Qt.EditRole)
else:
return False
else:
return QSqlTableModel.setData(self, index, value, role)
def flags(self, index):
if not index.isValid():
return Qt.NoItemFlags
if index.column() in self.booleanSet:
return Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsEditable
elif index.column() in self.readOnlySet:
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
else:
return QSqlTableModel.flags(self, index)
class ReadOnlyDelegate(QItemDelegate):
def createEditor(self, parent, option, index):
lb = QLabel(parent)
return lb
if __name__ == '__main__':
app = QApplication(sys.argv)
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("/path/of/your_database.db")
if not db.open():
sys.exit(-1)
model = ImportSqlTableModel()
w = QTableView()
w.setModel(model)
for col in model.booleanSet:
w.setItemDelegateForColumn(col, ReadOnlyDelegate(w))
w.show()
sys.exit(app.exec_())
The fault regarding the different QSqlDatabase object's was in the call of the subclassed QSqlTableModel. It must be assignedModel = YourSubclassedTableModel(db=your_open_database_object) if the source is a physical db. If the database is in memory db.setDatabaseName(':memory:') then this db is the default db and will be used inside the model. The docs don't mention that. In the Qt manual you will find:
QSqlTableModel::QSqlTableModel(QObject *parent = Q_NULLPTR, QSqlDatabase db = QSqlDatabase())
Creates an empty QSqlTableModel and sets the parent to parent and the database connection to db. If db is not valid, the default database connection will be used.
I'm new to PyQt. So I'm trying to get selected item from QListView, I'm able to get selected items's index, but I'm not able to get the value of the index, can please someone help me.
Here is the code :
import sys
import os
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class asset(QtGui.QDialog):
def __init__(self,parent=None):
super(asset, self).__init__(parent)
self.assetList = QtGui.QListView(self)
self.assetList.clicked.connect(self.on_treeView_clicked)
######################################################################
# ----------------- ADD ITEMS----------------------------------------
######################################################################
list_data = listDirs('D:\\')
dir = listModel(list_data)
self.assetList.setModel(dir)
self.setStyleSheet('''
*{
background-color : rgb(65,65,65);
color : rgb(210,210,210);
alternate-background-color:rgb(55,55,55);
}
QTreeView,QListView,QLineEdit{
background-color : rgb(50,50,50);
color : rgb(210,210,210);
}
'''
)
self.setFocus()
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_clicked(self, index):
itms = self.assetList.selectedIndexes()
for it in itms:
print 'selected item index found at %s' % it.row()
class listModel(QAbstractListModel):
def __init__(self, datain, parent=None, *args):
""" datain: a list where each item is a row
"""
QAbstractListModel.__init__(self, parent, *args)
self.listdata = datain
def rowCount(self, parent=QModelIndex()):
return len(self.listdata)
def data(self, index, role):
if index.isValid() and role == Qt.DisplayRole:
return QVariant(self.listdata[index.row()])
else:
return QVariant()
def listDirs(*path):
completePath = os.path.join(*path)
dirs = os.listdir(os.path.abspath(completePath))
outputDir = []
for dir in dirs:
if os.path.isdir(os.path.join(completePath,dir)):
outputDir.append(dir)
return outputDir
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setStyle('plastique')
main = asset()
main.resize(200,200)
main.show()
sys.exit(app.exec_())
Thanks !
You can use the convenience method data of QModelIndex. It returns a QVariant. Just convert it to something you'd use, like a QString with .toString:
print 'selected item index found at %s with data: %s' % (it.row(), it.data().toString())
By the way, QListView.clicked will give you the index. Unless you have multiple selection, or override the default selection behavior, it will be the only selected item. You don't need to loop over selectedIndexes():
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_clicked(self, index):
print 'selected item index found at %s with data: %s' % (index.row(), index.data().toString())