PDA

View Full Version : [PyQt4] Drag and drop rows with QTableView and QSqlTableModel



primus454
12th September 2015, 10:13
Hi I am trying to drag and drop single rows internally by clicking on any item in the row. I can't seem to get this to work. I can make them sortable by making the HEADERS movable, but then I must click on the header to initiate the drag which is not desirable. Here is a working example:


import os, sys
from PyQt4 import QtCore, QtGui, QtSql

def makeDB():
import sqlite3
db = sqlite3.connect("db.db")
db.execute("create table if not exists table1 (value text, data text)")

query = "insert into table1 (value, data) values (?, ?)"

valueSet = (("day","today"),("time","noon"),("food","cheese"))
for values in valueSet:
db.execute(query, values)
db.commit()

class TestApp(QtGui.QDialog):
def __init__(self, model, parent = None):
super(TestApp, self).__init__(parent)
self.model = model

table = QtGui.QTableView()
table.setModel(self.model)
table.setSortingEnabled(True)
table.setDropIndicatorShown(True)
table.setAcceptDrops(True)
table.setDragEnabled(True)
table.setSelectionMode(QtGui.QTableView.SingleSele ction)
table.setSelectionBehavior(QtGui.QTableView.Select Rows)
table.setDragDropMode(QtGui.QAbstractItemView.Inte rnalMove)
'''table.horizontalHeader().setMovable(True)
table.horizontalHeader().setDragEnabled(True)
table.horizontalHeader().setDragDropMode(QtGui.QAb stractItemView.InternalMove)
table.verticalHeader().setMovable(True)
table.verticalHeader().setDragEnabled(True)
table.verticalHeader().setDragDropMode(QtGui.QAbst ractItemView.InternalMove)
'''
layout = QtGui.QVBoxLayout(self)
layout.addWidget(table)


class myModel(QtSql.QSqlTableModel):
def __init__(self, parent = None):
super(myModel, self).__init__(parent)
self.setEditStrategy(QtSql.QSqlTableModel.OnFieldC hange)

self.setTable("table1")
self.select()

if __name__ == "__main__":
if not os.path.exists("db.db"):
makeDB()

myDb = QtSql.QSqlDatabase.addDatabase("QSQLITE")
myDb.setDatabaseName("db.db")
model = myModel()

app = QtGui.QApplication(sys.argv)
dl = TestApp(model)
dl.exec_()

primus454
12th September 2015, 15:42
Adding the follow to the model subclass allows the drag to start, but I cannot drop them:


def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsDropEnabled