How to set column index in QSqlTableModel - python

this time I want to change the default index of the QSqlTableModel that I have, in addition to the code, I attach an image of the result.
My code is:
import sys
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtSql import QSqlTableModel, QSqlDatabase
from PyQt6.QtWidgets import QApplication, QTableView
class CustomSqlModel(QSqlTableModel):
def __init__(self, parent=None):
QSqlTableModel.__init__(self, parent=parent)
self.setTable("entities")
self.setEditStrategy(QSqlTableModel.EditStrategy.OnFieldChange)
self.select()
def data(self, item, role):
val = QSqlTableModel.data(self, item, role)
if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
if item.column() == 3:
try:
return str(int(val))
except ValueError:
pass
if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
if item.column() == 2:
try:
return str(int(val))
except ValueError:
pass
return val
if __name__ == '__main__':
app = QApplication(sys.argv)
db = QSqlDatabase.addDatabase('QPSQL')
db.setDatabaseName("impulsadb")
db.setHostName('myhost')
db.open('myid','mypass')
model = CustomSqlModel()
view = QTableView()
view.resizeColumnsToContents()
view.setBaseSize(600,800)
view.setModel(model)
view.setWindowTitle("Custom Model")
view.show()
sys.exit(app.exec())
By placing my host and my credentials, the following results in this model
I want to set entity_id column as index column.

Related

PySide6: column of checkboxes for a boolean variable in a data table [duplicate]

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.

Exporting filter results QTableView (Python)

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

How to subclass QSqlTableModel in pyqt5?

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.

qtableview add rows from a query and edit them in python

i use Python 2.7, MariaDB and Qt4. I have a table in which i want to insert rows from a query. I tried self.model = QtSql.QSqlQueryModel() but i found that this is only read only. Then i moved to something else.
My Model() class looks like this:
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
query = QtSql.QSqlQuery()
query.prepare("SELECT denumire,pret_in,pret_out,cantitate,unitate_masura,tax FROM produse WHERE denumire='"+str(self.run_denumire())+"';")
query.exec_()
while(query.next()):
nume_produs = str(query.value(0).toString())
pret_in = str(query.value(1).toString())
pret_out = str(query.value(2).toString())
cantitate = str(query.value(3).toString())
unitate_masura = str(query.value(4).toString())
tax_tva = str(query.value(5).toString())
self.items = [nume_produs,pret_in,pret_out,cantitate,unitate_masura]
def rowCount(self, parent=QModelIndex()):
return 1
def columnCount(self, parent=QModelIndex()):
return len(self.items)
def data(self, index, role):
if not index.isValid(): return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
column=index.column()
if column<len(self.items):
return QVariant(self.items[column])
else:
return QVariant()
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
I am new to Qt and i don't know how to insert rows one by one to appear on table. What you see here is a code found by me here on stackoverflow and i modified it with a query . I need some help on this .
My main code is like this:
import time,os.path, os,module
from PyQt4 import QtGui, uic,QtSql,QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class dialog_receptie(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
file_path = os.path.abspath("ui/receptie.ui")
uic.loadUi(file_path, self)
self.move(QtGui.QApplication.desktop().screen().rect().center() - self.rect().center())
My ui file is:file
The file was made by Qt Designer.
Thank you.
UPDATE 1:
I inserted in class dialog_receptie a function. It looks like this:
def show_lista_receptie(self):
# self.model = QtSql.QSqlQueryModel()
# self.model.setQuery("SELECT den_produs,concat(pret_in,' Lei'),concat(pret_out,' Lei'),val_tva,cantitate,um FROM receptie_temp;")
self.model = QtSql.QSqlTableModel()
self.model.setTable("produse")
self.model.setQuery("SELECT * FROM receptie_temp;")
self.model.setHeaderData(1, QtCore.Qt.Horizontal, self.tr("Produs "))
self.model.setHeaderData(4, QtCore.Qt.Horizontal, self.tr("Pret cumparare "))
self.model.setHeaderData(5, QtCore.Qt.Horizontal, self.tr("Pret vanzare "))
self.model.setHeaderData(6, QtCore.Qt.Horizontal, self.tr("TVA Produs "))
self.model.setHeaderData(7, QtCore.Qt.Horizontal, self.tr("Cantitate "))
self.model.setHeaderData(11, QtCore.Qt.Horizontal, self.tr("UM "))
self.produse_view.setModel(self.model)
self.produse_view.hideColumn(0) # hide id column
self.produse_view.hideColumn(2)
self.produse_view.hideColumn(3)
self.produse_view.hideColumn(8)
self.produse_view.hideColumn(9)
self.produse_view.hideColumn(10)
self.produse_view.hideColumn(12)
If i use this line self.model.setQuery("SELECT * FROM receptie_temp;") i get an error message:
File "E:\onedrive\Documents\optimpos\module\receptie.py", line 64, in show_lista_receptie
self.model.setQuery("SELECT * FROM receptie_temp;")
TypeError: setQuery(self, QSqlQuery): argument 1 has unexpected type 'str'
How can query data from receptie_temp table without using an array? And how are the edited values in the table updated to the sql table?
Thank You.
I recommend using the QSqlTableModel class:
The QSqlTableModel class provides an editable data model for a single
database table.
In your case:
import os
import sys
from PyQt4 import QtGui, uic, QtSql
from PyQt4.QtGui import *
class dialog_receptie(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
file_path = os.path.abspath("ui/receptie.ui")
uic.loadUi(file_path, self)
# self.move(QtGui.QApplication.desktop().screen().rect().center() - self.rect().center())
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName(HOSTNAME);
db.setDatabaseName(DATABASE);
db.setUserName(USER);
db.setPassword(PASSWORD)
self.model = QtSql.QSqlTableModel()
self.model.setTable("produse")
self.produse_view.setModel(self.model)
self.produse_view.hideColumn(0) # hide id column
self.addData(["a", "b", "c", "d", "e", "f"])
def addData(self, data):
rec = self.model.record()
for i in range(6):
rec.setValue(rec.field(i+1).name(), data[i])
self.model.insertRecord(-1, rec)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = dialog_receptie()
w.show()
sys.exit(app.exec_())

How to get item selected from QListView in PyQt

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())

Categories