How to select QTableView row with one click - python

When one of the QTableView's QModelIndex is clicked I want to select an entire row of the same-row-indexes.
To accomplish this I connect QTableView's clicked signal to a custom viewClicked() method which receives the clicked QModelIndex automatically:
self.tableview=QTableView()
self.tableview.clicked.connect(self.viewClicked)
Inside of viewClicked(self, clickedIndex) I query clickedIndex's row number, its model and the total number of columns):
row=clickedIndex.row()
model=clickedIndex.model()
columnsTotal=model.columnCount(None)
Finally to select an every index in a row:
for i in range(columnsTotal): self.tableview.selectRow(row)
The problem is it is noticeably slow for Qt to process such an action.
I wonder if there is a faster way to select an entire row of indexes when one of the tableview items is clicked:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.items = ['Row0_Column0','Row0_Column1','Row0_Column2']
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
def rowCount(self, parent):
return 1
def columnCount(self, parent):
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()
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
tablemodel=Model(self)
self.tableview=QTableView()
self.tableview.setModel(tablemodel)
self.tableview.clicked.connect(self.viewClicked)
layout = QHBoxLayout(self)
layout.addWidget(self.tableview)
self.setLayout(layout)
def viewClicked(self, clickedIndex):
row=clickedIndex.row()
model=clickedIndex.model()
columnsTotal=model.columnCount(None)
for i in range(columnsTotal):
self.tableview.selectRow(row)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
EDITED LATER: REVISED WORKING CODE Thanks to Nejat! :
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.items = ['Row0_Column0','Row0_Column1','Row0_Column2']
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
def rowCount(self, parent):
return 1
def columnCount(self, parent):
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()
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
tablemodel=Model(self)
self.tableview=QTableView()
self.tableview.setModel(tablemodel)
self.tableview.clicked.connect(self.viewClicked)
self.tableview.setSelectionBehavior(QTableView.SelectRows)
layout = QHBoxLayout(self)
layout.addWidget(self.tableview)
self.setLayout(layout)
def viewClicked(self, clickedIndex):
row=clickedIndex.row()
model=clickedIndex.model()
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())

You can use setSelectionBehavior function of QTableView to set the selection behavior to QTableView.SelectRows :
self.tableview.setSelectionBehavior(QTableView.SelectRows);
Now when you click on an item, the entire row is selected.

Related

How can dynamically add headers to table in this pyqt5 app?

This code I have taken from https://bravo.hatenablog.jp/entry/2016/01/18/093059 .
In this I want to add header "Quantity" at run time if needed.
Before creating table it should ask for how many headers? If user supply 4 then create table with "Quantity" headers also. Otherwise create default headers (Three).
I have tried it but not found any solution.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Model(QAbstractItemModel):
headers = "Toppings", "Udon/Soba", "Hot/Cold"
def __init__(self, parent=None):
super(Model, self).__init__(parent)
self.items = []
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column, None)
def parent(self, child):
return QModelIndex()
def rowCount(self, parent=QModelIndex()):
return len(self.items)
def columnCount(self, parent=QModelIndex()):
return len(self.headers)
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
try:
return self.items[index.row()][index.column()]
except:
return
return
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return
if orientation == Qt.Horizontal:
return self.headers[section]
def addRow(self, topping, menkind, hotcold):
self.beginInsertRows(QModelIndex(), len(self.items), 1)
self.items.append([topping, menkind, hotcold])
self.endInsertRows()
def removeRows(self, rowIndexes):
for row in sorted(rowIndexes, reverse=True):
self.beginRemoveRows(QModelIndex(), row, row + 1)
del self.items[row]
self.endRemoveRows()
def flags(self, index):
return super(Model, self).flags(index) | Qt.ItemIsEditable
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.EditRole:
self.items[index.row()][index.column()] = value
return True
return False
class View(QTreeView):
def __init__(self, parent=None):
super(View, self).__init__(parent)
self.setItemsExpandable(False)
self.setIndentation(0)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
def drawBranches(self, painter, rect, index):
return
class InputWidget(QWidget):
def __init__(self, parent=None):
super(InputWidget, self).__init__(parent)
layout = QVBoxLayout()
toppings = ("Kitsune", "Tanuki", "Tempura", "Tsukimi", "Meat", "Curry")
self.toppingInput = QComboBox()
for topping in toppings:
self.toppingInput.addItem(topping)
layout.addWidget(self.toppingInput)
self.bgrp = QGroupBox()
udon = QRadioButton('Udon')
udon.setChecked(True)
soba = QRadioButton('Soba')
btnlayout = QHBoxLayout()
btnlayout.addWidget(udon)
btnlayout.addWidget(soba)
self.bgrp.setLayout(btnlayout)
layout.addWidget(self.bgrp)
self.udonsoba = udon, soba
self.bgrp_temp = QGroupBox()
hot = QRadioButton('Warm')
hot.setChecked(True)
cold = QRadioButton('Cold')
btnlayout_temp = QHBoxLayout()
btnlayout_temp.addWidget(hot)
btnlayout_temp.addWidget(cold)
self.bgrp_temp.setLayout(btnlayout_temp)
layout.addWidget(self.bgrp_temp)
self.hotcold = hot, cold
self.addButton = QPushButton('OK')
layout.addWidget(self.addButton)
layout.addStretch()
self.setLayout(layout)
def values(self):
topping = self.toppingInput.currentText()
udonsoba = '?'
for btn in self.udonsoba:
if btn.isChecked():
udonsoba = btn.text()
break
hotcold = '?'
for btn in self.hotcold:
if btn.isChecked():
hotcold = btn.text()
break
return topping, udonsoba, hotcold
class Delegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(Delegate, self).__init__(parent)
def createEditor(self, parent, option, index):
return QLineEdit(parent)
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.DisplayRole)
editor.setText(value)
def setModelData(self, editor, model, index):
model.setData(index, editor.text())
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.view = View(self)
self.model = Model(self)
self.view.setModel(self.model)
self.view.setItemDelegate(Delegate())
self.setCentralWidget(self.view)
self.inputWidget = InputWidget()
self.inputWidget.addButton.clicked.connect(self.addItem)
self.addDock = QDockWidget('Input', self)
self.addDock.setWidget(self.inputWidget)
self.addDock.setAllowedAreas(Qt.AllDockWidgetAreas)
self.addDockWidget(Qt.RightDockWidgetArea, self.addDock)
self.addDock.hide()
toolBar = QToolBar()
self.addToolBar(toolBar)
delButton = QPushButton('Delete')
delButton.clicked.connect(self.removeItems)
toolBar.addWidget(delButton)
self.addButton = QPushButton('Add')
self.addButton.clicked.connect(self.addDock.show)
toolBar.addWidget(self.addButton)
def addItem(self):
self.model.addRow(*self.inputWidget.values())
def selectedRows(self):
rows = []
for index in self.view.selectedIndexes():
if index.column() == 0:
rows.append(index.row())
return rows
def removeItems(self):
self.model.removeRows(self.selectedRows())
def main():
app = QApplication(sys.argv)
w = MainWindow()
w.show()
w.raise_()
app.exec_()
if __name__ == '__main__':
main()

PyQt5 TableModel(QAbstractTableModel) shows no data

Hello i started with PyQt5 recently and tried to implement a csv parser:
But i struggled with the descendant of the QAbstractTableModel.
No data in the view!
The tutorial from qt5 (https://doc.qt.io/qt-5/qabstracttablemodel.html) says i have to implement some methods in the TableModel - class.
I think i did that but - no data in the view.
from PyQt5.QtWidgets import \
QApplication, QWidget, QVBoxLayout, QTableView
from PyQt5.QtCore import \
QAbstractTableModel, QVariant, Qt
class TableModel(QAbstractTableModel):
def __init__(self):
super().__init__()
self._data = []
def set(self, data):
self._data = data
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
elif role == Qt.DisplayRole:
row = index.row()
return self._data[row]
else:
return QVariant()
def headerData(self, p_int, Qt_Orientation, role=None):
return self._data[0]
class View(QWidget):
def __init__(self):
super().__init__()
model = TableModel()
model.set(data)
self.tbl = QTableView(self)
self.tbl.setModel(model)
def setup(self):
self.setMinimumHeight(600)
self.setMinimumWidth(800)
self.vlayout = QVBoxLayout(self)
self.vlayout.addWidget(self.tbl)
def main():
import sys
app = QApplication(sys.argv)
window = View()
window.setup()
window.show()
sys.exit(app.exec_())
main()
Some Mock data from here:
data = [f.strip().split(",") for f in """\
id,first_name,last_name,email,gender,ip_address
1,Hillard,Tasseler,htasseler0#google.com.br,Male,104.153.237.243
2,Tyrus,Oley,toley1#ft.com,Male,163.73.24.45
3,Kora,Covil,kcovil2#privacy.gov.au,Female,158.44.166.87
4,Phineas,McEntee,pmcentee3#rambler.ru,Male,71.82.246.45
5,Dottie,Spraging,dspraging4#berkeley.edu,Female,226.138.241.22
6,Andria,Ivatts,aivatts5#about.com,Female,57.5.76.78
7,Missy,Featherstone,mfeatherstone6#unblog.fr,Female,9.56.215.203
8,Anstice,Sargant,asargant7#about.me,Female,36.115.185.109
9,Teresita,Trounce,ttrounce8#myspace.com,Female,240.228.133.166
10,Sib,Thomke,sthomke9#ibm.com,Female,129.191.2.7
11,Amery,Dallander,adallandera#elpais.com,Male,4.115.194.100
12,Rourke,Rowswell,rrowswellb#bloomberg.com,Male,48.111.190.66
13,Cloe,Benns,cbennsc#slideshare.net,Female,142.48.24.44
14,Enos,Fery,eferyd#pen.io,Male,59.19.200.235
15,Russell,Capelen,rcapelene#fc2.com,Male,38.205.20.141""".split()]
The data method must return a value as a string, not a list, in your case self._data[row] is a list so the solution is to use the column to obtain a single element from that list:
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
elif role == Qt.DisplayRole:
row = index.row()
col = index.column()
return self._data[row][col]
else:
return QVariant()

How to extend Qt Widgets that do not have model support by default

CustomMenu class inherits from QMenu. Its custom setData() method accepts an argument and sets it to a class variable model. I did this because QToolButton, QToolMenu and QAction do not support model/view framework. From what I know aside from all QList-QTable-QTree Views and Trees only the QComboBox does support model.
So the question: would it be possible to extend the functionality of other non-model widgets so they could be used as driven-by-model widgets too?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os
class CustomMenu(QMenu):
def __init__(self):
super(CustomMenu, self).__init__()
self.model=None
def setModel(self, model):
self.model=model
self.pupulate()
def pupulate(self):
for item in self.model.items:
self.addAction(item)
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.items = ['Row0_Column0','Row1_Column0','Row2_Column0']
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
def rowCount(self, QModelIndex):
return len(self.items)
def columnCount(self, QModelIndex):
return 1
def data(self, index, role):
if not index.isValid(): return QVariant()
if role == Qt.DisplayRole:
return QVariant(self.items[index.row()])
return QVariant()
def setData(self, index, value, role=Qt.EditRole):
if index.isValid():
if role == Qt.EditRole:
self.items[index.row()]=value
return True
return False
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
layout=QVBoxLayout(self)
self.setLayout(layout)
tablemodel=Model(self)
tableView=QTableView()
tableView.horizontalHeader().setStretchLastSection(True)
tableView.setModel(tablemodel)
layout.addWidget(tableView)
combo=QComboBox()
combo.setModel(tablemodel)
layout.addWidget(combo)
toolButton=QToolButton(self)
toolButton.setText('Tool Button')
toolButton.setPopupMode(QToolButton.InstantPopup)
toolButton.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed))
menu=CustomMenu()
menu.setModel(tablemodel)
toolButton.setMenu(menu)
layout.addWidget(toolButton)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
EDITED LATER: An attempt to implement a QDataWidgetMapper():
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os
class CustomMenuButton(QWidget):
def __init__(self, parent):
super(CustomMenuButton, self).__init__(parent)
self.dataMapper=QDataWidgetMapper()
layout=QVBoxLayout()
self.setLayout(layout)
toolButton=QToolButton(self)
toolButton.setText('Tool Button')
toolButton.setPopupMode(QToolButton.InstantPopup)
self.menu=QMenu(toolButton)
toolButton.setMenu(self.menu)
def setModel(self, model):
self.dataMapper.setModel(model)
for row in range(model.rowCount()):
action=self.menu.addAction('Item')
self.dataMapper.addMapping(action, row)
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.items = ['Row0_Column0','Row1_Column0','Row2_Column0']
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
def rowCount(self, parent=QModelIndex()):
return len(self.items)
def columnCount(self, parent=QModelIndex()):
return 1
def data(self, index, role):
if not index.isValid(): return QVariant()
if role == Qt.DisplayRole:
return QVariant(self.items[index.row()])
return QVariant()
def setData(self, index, value, role=Qt.EditRole):
if index.isValid():
if role == Qt.EditRole:
self.items[index.row()]=value
self.dataChanged.emit(index, index)
return True
return False
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
layout=QVBoxLayout(self)
self.setLayout(layout)
tablemodel=Model(self)
tableView=QTableView()
tableView.horizontalHeader().setStretchLastSection(True)
tableView.setModel(tablemodel)
layout.addWidget(tableView)
combo=QComboBox()
combo.setModel(tablemodel)
layout.addWidget(combo)
menuButton=CustomMenuButton(self)
layout.addWidget(menuButton)
menuButton.setModel(tablemodel)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
EDIT 2: Defined a class CustomAction(QAction) with dataChanged = pyqtSignal(QModelIndex,QModelIndex)...
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os
class CustomAction(QAction):
dataChanged = pyqtSignal(QModelIndex,QModelIndex)
def __init__(self, name, parent):
super(CustomAction, self).__init__(name, parent)
class CustomMenuButton(QWidget):
def __init__(self, parent):
super(CustomMenuButton, self).__init__(parent)
self.dataMapper=QDataWidgetMapper()
layout=QVBoxLayout()
self.setLayout(layout)
toolButton=QToolButton(self)
toolButton.setText('Tool Button')
toolButton.setPopupMode(QToolButton.InstantPopup)
self.menu=QMenu(toolButton)
toolButton.setMenu(self.menu)
def setModel(self, model):
self.dataMapper.setModel(model)
for row in range(model.rowCount()):
index=model.index(row,0)
itemName=model.data(index, Qt.DisplayRole).toPyObject()
actn=CustomAction(itemName, self.menu)
self.menu.addAction(actn)
self.dataMapper.addMapping(actn, row)
class Model(QAbstractTableModel):
def __init__(self, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.items = ['Row0_Column0','Row1_Column0','Row2_Column0']
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
def rowCount(self, parent=QModelIndex()):
return len(self.items)
def columnCount(self, parent=QModelIndex()):
return 1
def data(self, index, role):
if not index.isValid(): return QVariant()
if role == Qt.DisplayRole:
return QVariant(self.items[index.row()])
return QVariant()
def setData(self, index, value, role=Qt.EditRole):
if index.isValid():
if role == Qt.EditRole:
self.items[index.row()]=value
self.dataChanged.emit(index, index)
return True
return False
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
layout=QVBoxLayout(self)
self.setLayout(layout)
tablemodel=Model(self)
tableView=QTableView()
tableView.horizontalHeader().setStretchLastSection(True)
tableView.setModel(tablemodel)
layout.addWidget(tableView)
combo=QComboBox()
combo.setModel(tablemodel)
layout.addWidget(combo)
menuButton=CustomMenuButton(self)
layout.addWidget(menuButton)
menuButton.setModel(tablemodel)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
This is what the QDataWidgetMapper class was designed for. The following blog has a great tutorial covering exactly how to implement it: http://www.yasinuludag.com/blog/?p=98
EDIT: I should add that QDataWidgetMapper works with QWidget and its subclasses, so QAction would not apply. For classes that are not QWidget or its subclasses, you might have to implement your own custom model-view binding.

Make checkbox by QAbstractTableModel

I want to make the first column with checkbox, and get the check status of that, how can I do that? I override the flag(), but it seems do not work, I am sure where is the problem?
And I got this links, but it does work for my code either. And I don't want to use delegate, because it is too complicated.
data = [['00','01','02'],
['10','11','12'],
['20','21','22']]
class MainWindow(QWidget):
def __init__(self, parent=None, *args):
super(MainWindow, self).__init__(parent)
clipTableWidget = QTableWidget()
self.model = TModel(data, self)
clipTableView = QTableView()
clipTableView.setModel(self.model)
layout = QVBoxLayout()
layout.addWidget(clipTableView)
self.setLayout(layout)
class TModel(QAbstractTableModel):
def __init__(self, datain, parent=None):
super(TModel, self).__init__(parent)
self.arraydata = datain
def rowCount(self, parent=QModelIndex()):
return len(self.arraydata)
def columnCount(self, parent=QModelIndex()):
return len(self.arraydata[0])
def data(self, index, role):
if not index.isValid():
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
def flags(self, index):
if not index.isValid():
return QVariant()
elif index.column() == 1:
return Qt.ItemIsSelectable|Qt.ItemIsEnabled|Qt.ItemIsUserCheckable
return QVariant()
Ok here is the solution to your problem. The reason Why your flags weren't working is because those flags dont work on text , they are meant for QItems .
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MainWindow(QWidget):
def __init__(self, parent=None, *args):
super(MainWindow, self).__init__(parent)
data = [['00','01','02'],
['10','11','12'],
['20','21','22']]
clipTableWidget = QTableWidget()
self.model = QStandardItemModel(self)
clipTableView = QTableView()
count1=0
for row in data:
count2 = 0
for column in row:
if count2 == 0:
item = QStandardItem(column)
item.setCheckable(True)
item.setCheckState(False)
item.setFlags(Qt.ItemIsUserCheckable| Qt.ItemIsEnabled)
self.model.setItem(count1,count2,item)
count2+=1
else:
item = QStandardItem(column)
self.model.setItem(count1,count2,item)
count2+=1
count1+=1
clipTableView.setModel(self.model)
layout = QVBoxLayout()
layout.addWidget(clipTableView)
self.setLayout(layout)
def main():
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

QTreeView with drag and drop support in PyQt

In PyQt 4 I would like to create a QTreeView with possibility to reorganize its structure with drag and drop manipulation.
I have implemented my own model(QAbstractItemModel) for QTreeView so my QTreeView properly displays the data.
Now I would like to add drag and drop support for tree's nodes to be able to move a node inside the tree from one parent to another one, drag-copy and so on, but I cannot find any complete tutorial how to achieve this. I have found few tutorials and hints for QTreeWidget, but not for QTreeView with custom model.
Can someone point me where to look?
Thank you.
You can enable drag and drop support for tree view items by setting QtGui.QAbstractItemView.InternalMove into the dragDropMode property of the treeview control. Also take a look at the documentation here Using drag & drop with item views. Below is a small example of a treeview with internal drag and drop enabled for its items.
import sys
from PyQt4 import QtGui, QtCore
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.model = QtGui.QStandardItemModel()
for k in range(0, 4):
parentItem = self.model.invisibleRootItem()
for i in range(0, 4):
item = QtGui.QStandardItem(QtCore.QString("item %0 %1").arg(k).arg(i))
parentItem.appendRow(item)
parentItem = item
self.view = QtGui.QTreeView()
self.view.setModel(self.model)
self.view.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setCentralWidget(self.view)
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
Edit0: treeview + abstract model with drag and drop support
import sys
from PyQt4 import QtGui, QtCore
class TreeModel(QtCore.QAbstractItemModel):
def __init__(self):
QtCore.QAbstractItemModel.__init__(self)
self.nodes = ['node0', 'node1', 'node2']
def index(self, row, column, parent):
return self.createIndex(row, column, self.nodes[row])
def parent(self, index):
return QtCore.QModelIndex()
def rowCount(self, index):
if index.internalPointer() in self.nodes:
return 0
return len(self.nodes)
def columnCount(self, index):
return 1
def data(self, index, role):
if role == 0:
return index.internalPointer()
else:
return None
def supportedDropActions(self):
return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction
def flags(self, index):
if not index.isValid():
return QtCore.Qt.ItemIsEnabled
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | \
QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled
def mimeTypes(self):
return ['text/xml']
def mimeData(self, indexes):
mimedata = QtCore.QMimeData()
mimedata.setData('text/xml', 'mimeData')
return mimedata
def dropMimeData(self, data, action, row, column, parent):
print 'dropMimeData %s %s %s %s' % (data.data('text/xml'), action, row, parent)
return True
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.treeModel = TreeModel()
self.view = QtGui.QTreeView()
self.view.setModel(self.treeModel)
self.view.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setCentralWidget(self.view)
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
hope this helps, regards

Categories

Resources