QDataWidgetMapper; mapping TableWidget to model - python-3.x

I am not finding any documentation showing which widgets QDataWidgetMapper actually works for and have not found any implementation of mapping with a QTableWidget.
It definitely works for QLineEdit's and QComboBoxes, which are input widgets, but is it possible to map to a QTableWidget?
Goal is to use QUndoStack to undo/redo text change in each widget when added to the QUndostack. I want to be able to undo/redo text changes for the items in the QTableWidget as well as the QLineEdits and QComboBoxes.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class CommandTextEdit(QtWidgets.QUndoCommand):
def __init__(self, window, index, oldText, newText, description):
super(CommandTextEdit,self).__init__()
self.index = index
self.window = window
self.oldText = oldText
self.newText = newText
def redo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.newText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
def undo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.oldText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
class Model(QtCore.QAbstractListModel):
itemDataChanged = QtCore.pyqtSignal(object,object, object, object)
def __init__(self, text = [], parent = None):
super(Model,self).__init__(parent)
self._text = text
def rowCount(self,parent=QtCore.QModelIndex()):
return len(self._text)
def data(self,index,role):
row = index.row()
if role == QtCore.Qt.EditRole:
return self._text[row]
if role == QtCore.Qt.DisplayRole:
value = self._text[row]
return self._text[row]
def model(self):
return self
def flags(self, index):
return QtCore.Qt.ItemIsEditable |QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role = QtCore.Qt.UserRole + 1):
if index.isValid():
if role == QtCore.Qt.EditRole:
oldValue = self.data(index,role)
self._text[index.row()] = value
self.dataChanged.emit(index, index)
if oldValue != value:
self.itemDataChanged.emit(index, oldValue, value, role)
return True
return False
class Window(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(Window,self).__init__(parent)
self.setCentralWidget(QtWidgets.QWidget(self))
self.setWindowTitle('Widget Mapping GUI')
mainlayout = QtWidgets.QVBoxLayout()
#Information for widgets
items = ["","H","N","M"]
#LineEdit1
self.labelLineEdit1 = QtWidgets.QLabel()
self.labelLineEdit1.setText('LineEdit1')
self.LineEdit1 = QtWidgets.QLineEdit()
firstBox = QtWidgets.QHBoxLayout()
firstBox.addWidget(self.labelLineEdit1)
firstBox.addWidget(self.LineEdit1)
#LineEdit2
self.labelLineEdit2 = QtWidgets.QLabel()
self.labelLineEdit2.setText('LineEdit2')
self.LineEdit2 = QtWidgets.QLineEdit()
secondBox = QtWidgets.QHBoxLayout()
secondBox.addWidget(self.labelLineEdit2)
secondBox.addWidget(self.LineEdit2)
#ComboBox1
self.labelComboBox1 = QtWidgets.QLabel()
self.labelComboBox1.setText('ComboBox1')
self.ComboBox1 = QtWidgets.QComboBox()
self.ComboBox1.addItems(items)
thirdBox = QtWidgets.QHBoxLayout()
thirdBox.addWidget(self.labelComboBox1)
thirdBox.addWidget(self.ComboBox1)
#ComboBox2
self.labelComboBox2 = QtWidgets.QLabel()
self.labelComboBox2.setText('ComboBox2')
self.ComboBox2 = QtWidgets.QComboBox()
self.ComboBox2.addItems(items)
fourthBox = QtWidgets.QHBoxLayout()
fourthBox.addWidget(self.labelComboBox2)
fourthBox.addWidget(self.ComboBox2)
#TableWidget
self.TableWidget = QtWidgets.QTableWidget(5,1)
#Set header labels
self.TableWidget.setHorizontalHeaderLabels(["Dimensions"])
self.TableWidget.setVerticalHeaderLabels(["A","B","C","D","E"])
self.TableWidget.setItem(0,1,QtWidgets.QTableWidgetItem('1'))
fifthBox = QtWidgets.QVBoxLayout()
fifthBox.addWidget(self.TableWidget)
#Add Layouts
mainlayout.addLayout(firstBox)
mainlayout.addLayout(secondBox)
mainlayout.addLayout(thirdBox)
mainlayout.addLayout(fourthBox)
mainlayout.addLayout(fifthBox)
self.centralWidget().setLayout(mainlayout)
#Model
self.mapper = None
self.model = Model(['','','','',''])
self.setModel(self.model)
#QUndoStack
self.undoStack = QtWidgets.QUndoStack()
self.stackView = QtWidgets.QUndoView(self.undoStack)
self.stackView.setWindowTitle('StackView')
self.stackView.show()
#Run init methods
self.createActions()
self.makeConnections()
self.listViewMethod()
def createActions(self):
self.UndoAct = QtWidgets.QAction("Undo", self)
self.UndoAct.setShortcut(QtGui.QKeySequence.Undo)
self.UndoAct.triggered.connect(self.undoStack.undo)
self.RedoAct = QtWidgets.QAction("Redo", self)
self.RedoAct.setShortcut(QtGui.QKeySequence.Redo)
self.RedoAct.triggered.connect(self.undoStack.redo)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(self.UndoAct)
self.toolbar.addAction(self.RedoAct)
def listViewMethod(self):
self.listView = QtWidgets.QListView()
self.listView.setModel(self.model)
self.listView.setWindowTitle('ListView')
self.listView.show()
def makeConnections(self):
self.model.itemDataChanged.connect(self.itemDataChangedSlot)
def setModel(self, model):
self.mapper = QtWidgets.QDataWidgetMapper(self)
self.mapper.setOrientation(QtCore.Qt.Vertical)
self.mapper.setModel(self.model)
self.mapper.addMapping(self.LineEdit1, 0)
self.mapper.addMapping(self.LineEdit2, 1)
self.mapper.addMapping(self.ComboBox1, 2)
self.mapper.addMapping(self.ComboBox2, 3)
self.mapper.addMapping(self.TableWidget,4)
self.mapper.toFirst()
def itemDataChangedSlot(self, index, oldValue, value, role):
if role == QtCore.Qt.EditRole:
command = CommandTextEdit(self, index, oldValue, value, "Text changed from '{0}' to '{1}'".format(oldValue, value))
self.undoStack.push(command)
def main():
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

To map the items of a QTableWidget, I used the setCellWidget method to map each cell to the model using a custom QLineEdit class.
Updated Code:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
#implemented stylesheets for QLineEdit to imitate a QTableWidgetItem
class CustomLineEdit(QtWidgets.QLineEdit):
def __init__(self):
super(CustomLineEdit,self).__init__()
self.setReadOnly(True)
self.setFrame(False)
self.setStyleSheet("QLineEdit { border: none; } \n" \
"QLineEdit::focus {background-color: #3daee9;} \n"\
"QLineEdit::focus::pressed {background-color: none;} \n"\
"QLineEdit::hover {background-color: #3daee9;}"
)
def mouseDoubleClickEvent(self,event):
self.setReadOnly(False)
self.setStyleSheet("QLineEdit { border: none; \nbackground-color: none;} \n" \
)
def focusOutEvent(self,event):
self.setReadOnly(True)
self.setStyleSheet("QLineEdit { border: none; } \n" \
"QLineEdit::focus {background-color: #3daee9;} \n"\
"QLineEdit::focus::pressed {background-color: none;} \n"\
"QLineEdit::hover {background-color: #3daee9;}"
)
class CommandTextEdit(QtWidgets.QUndoCommand):
def __init__(self, window, index, oldText, newText, description):
super(CommandTextEdit,self).__init__()
self.index = index
self.window = window
self.oldText = oldText
self.newText = newText
def redo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.newText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
def undo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.oldText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
class Model(QtCore.QAbstractListModel):
itemDataChanged = QtCore.pyqtSignal(object,object, object, object)
def __init__(self, text = [], parent = None):
super(Model,self).__init__(parent)
self._text = text
def rowCount(self,parent=QtCore.QModelIndex()):
return len(self._text)
def data(self,index,role):
row = index.row()
if role == QtCore.Qt.EditRole:
return self._text[row]
if role == QtCore.Qt.DisplayRole:
value = self._text[row]
return self._text[row]
def model(self):
return self
def flags(self, index):
return QtCore.Qt.ItemIsEditable |QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role = QtCore.Qt.UserRole + 1):
if index.isValid():
if role == QtCore.Qt.EditRole:
oldValue = self.data(index,role)
self._text[index.row()] = value
self.dataChanged.emit(index, index)
if oldValue != value:
self.itemDataChanged.emit(index, oldValue, value, role)
return True
return False
class Window(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(Window,self).__init__(parent)
self.setCentralWidget(QtWidgets.QWidget(self))
self.setWindowTitle('Widget Mapping GUI')
mainlayout = QtWidgets.QVBoxLayout()
#Information for widgets
items = ["","H","N","M"]
#LineEdit1
self.labelLineEdit1 = QtWidgets.QLabel()
self.labelLineEdit1.setText('LineEdit1')
self.LineEdit1 = QtWidgets.QLineEdit()
firstBox = QtWidgets.QHBoxLayout()
firstBox.addWidget(self.labelLineEdit1)
firstBox.addWidget(self.LineEdit1)
#LineEdit2
self.labelLineEdit2 = QtWidgets.QLabel()
self.labelLineEdit2.setText('LineEdit2')
self.LineEdit2 = QtWidgets.QLineEdit()
secondBox = QtWidgets.QHBoxLayout()
secondBox.addWidget(self.labelLineEdit2)
secondBox.addWidget(self.LineEdit2)
#ComboBox1
self.labelComboBox1 = QtWidgets.QLabel()
self.labelComboBox1.setText('ComboBox1')
self.ComboBox1 = QtWidgets.QComboBox()
self.ComboBox1.addItems(items)
thirdBox = QtWidgets.QHBoxLayout()
thirdBox.addWidget(self.labelComboBox1)
thirdBox.addWidget(self.ComboBox1)
#ComboBox2
self.labelComboBox2 = QtWidgets.QLabel()
self.labelComboBox2.setText('ComboBox2')
self.ComboBox2 = QtWidgets.QComboBox()
self.ComboBox2.addItems(items)
fourthBox = QtWidgets.QHBoxLayout()
fourthBox.addWidget(self.labelComboBox2)
fourthBox.addWidget(self.ComboBox2)
#TableWidget
self.TableWidget = QtWidgets.QTableWidget(5,1)
#Set header labels
self.TableWidget.setHorizontalHeaderLabels(["Dimensions"])
self.TableWidget.setVerticalHeaderLabels(["A","B","C","D","E"])
self.TableWidget.setCellWidget(0,0,CustomLineEdit())
self.TableWidget.setCellWidget(1,0,CustomLineEdit())
self.TableWidget.setCellWidget(2,0,CustomLineEdit())
self.TableWidget.setCellWidget(3,0,CustomLineEdit())
self.TableWidget.setCellWidget(4,0,CustomLineEdit())
self.TableWidget.setItem(1,0,QtWidgets.QTableWidgetItem('1'))
fifthBox = QtWidgets.QVBoxLayout()
fifthBox.addWidget(self.TableWidget)
#Add Layouts
mainlayout.addLayout(firstBox)
mainlayout.addLayout(secondBox)
mainlayout.addLayout(thirdBox)
mainlayout.addLayout(fourthBox)
mainlayout.addLayout(fifthBox)
self.centralWidget().setLayout(mainlayout)
#Model
self.mapper = None
self.model = Model(['' for i in range(9)])
self.setModel(self.model)
#QUndoStack
self.undoStack = QtWidgets.QUndoStack()
self.stackView = QtWidgets.QUndoView(self.undoStack)
self.stackView.setWindowTitle('StackView')
self.stackView.show()
#Run init methods
self.createActions()
self.makeConnections()
self.listViewMethod()
def createActions(self):
self.UndoAct = QtWidgets.QAction("Undo", self)
self.UndoAct.setShortcut(QtGui.QKeySequence.Undo)
self.UndoAct.triggered.connect(self.undoStack.undo)
self.RedoAct = QtWidgets.QAction("Redo", self)
self.RedoAct.setShortcut(QtGui.QKeySequence.Redo)
self.RedoAct.triggered.connect(self.undoStack.redo)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(self.UndoAct)
self.toolbar.addAction(self.RedoAct)
def listViewMethod(self):
self.listView = QtWidgets.QListView()
self.listView.setModel(self.model)
self.listView.setWindowTitle('ListView')
self.listView.show()
def makeConnections(self):
self.model.itemDataChanged.connect(self.itemDataChangedSlot)
def setModel(self, model):
self.mapper = QtWidgets.QDataWidgetMapper(self)
self.mapper.setOrientation(QtCore.Qt.Vertical)
self.mapper.setModel(self.model)
self.mapper.addMapping(self.LineEdit1, 0)
self.mapper.addMapping(self.LineEdit2, 1)
self.mapper.addMapping(self.ComboBox1, 2)
self.mapper.addMapping(self.ComboBox2, 3)
self.mapper.addMapping(self.TableWidget.cellWidget(0,0), 4)
self.mapper.addMapping(self.TableWidget.cellWidget(1,0), 5)
self.mapper.addMapping(self.TableWidget.cellWidget(2,0), 6)
self.mapper.addMapping(self.TableWidget.cellWidget(3,0), 7)
self.mapper.addMapping(self.TableWidget.cellWidget(4,0), 8)
self.mapper.toFirst()
def itemDataChangedSlot(self, index, oldValue, value, role):
if role == QtCore.Qt.EditRole:
command = CommandTextEdit(self, index, oldValue, value, "Text changed from '{0}' to '{1}'".format(oldValue, value))
self.undoStack.push(command)
def main():
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Related

KeyErrror: "parameter"

So I'm trying to implement a GUI in PyQT using a table, but for some reason I keep getting the error KeyError:"Parameter",
The dictionary uses variables from a decoded bin file that has data i would like to access an use
I'm very confused as i see no way forward, any help would be appreciated.
Below is my code
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
class DictionaryTableModel(QtCore.QAbstractTableModel):
def __init__(self, data, headers):
super(DictionaryTableModel, self).__init__()
self._data = data
self._headers = headers
def data(self, index, role):
if role == Qt.DisplayRole:
# Look up the key by header index.
column = index.column()
column_key = self._headers[column]
return self._data[index.row()][column_key]
def rowCount(self, index):
# The length of the outer list.
return len(self._data)
def columnCount(self, index):
# The length of our headers.
return len(self._headers)
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._headers[section])
if orientation == Qt.Vertical:
return str(section)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
with open("C:\\Ptests\\asdf\\bikeparametereditor\\uploaddomainobject.bin", 'rb') as file:
bytes2 = file.read()
# Read & Assign to variables
serialNumber = bytes2[0x1b:0x1b + 15].decode("utf-8")
frameNumber = bytes2[0x2a:0x3b].decode("utf-8")
productionDate = int.from_bytes(bytes2[0x3b:0x3e], byteorder="little")
hardwareVersion = bytes2[0x3f:0x49].decode("utf-8")
ssDO_KEY_LOCK = int.from_bytes(bytes2[0x49:0x49], byteorder="little")
coreDataVersion = int.from_bytes(bytes2[0x00:0x02], byteorder="little")
coreCRC = int.from_bytes(bytes2[0x03:0x06], byteorder="little")
coreTimeStamp = int.from_bytes(bytes2[0x07:0x09], byteorder="little")
coreAddrIndex = int.from_bytes(bytes2[0x09:0x11], byteorder="little")
coreSize = int.from_bytes(bytes2[0x20:0x21], byteorder="little")
coreWriteCounter = int.from_bytes(bytes2[0x21:0x22], byteorder="little")
corefailCounter = int.from_bytes(bytes2[0x22:0x23], byteorder="little")
data = [
{"serialNumber": serialNumber,
"frameNumber": frameNumber,
"productionDate": productionDate,
"hardwareVersion": hardwareVersion,
"coreDataVersion": coreDataVersion,
"coreCRC": coreCRC,
"coreTimeStamp": coreTimeStamp,
"coreAddrIndex": coreAddrIndex,
"coreSize": coreSize,
"coreWriteCounter": coreWriteCounter,
"corefailCounter": corefailCounter,
"ssDO_KEY_LOCK": ssDO_KEY_LOCK}
]
headers = ["parameter", "value"]
self.model = DictionaryTableModel(data, headers)
self.table.setModel(self.model)
self.setCentralWidget(self.table)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

How to use custome FilterProxyModel and QtCore.Qt.EditRole at a time?

Below is the example code:
class FilterProxyModel(QtCore.QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self._filter_value = None
#property
def filter_value(self):
return self._filter_value
#filter_value.setter
def filter_value(self, value):
self._filter_value = value
self.invalidateFilter()
def filterAcceptsRow(self, sourceRow, sourceParent):
if self.filter_value is None:
return super().filterAcceptsRow(sourceRow, sourceParent)
if self.filterKeyColumn() >= 0:
value = (
self.sourceModel()
.index(sourceRow, self.filterKeyColumn(), sourceParent)
.data(self.filterRole())
)
return value == self.filter_value
for column in range(self.columnCount()):
value = (
self.sourceModel()
.index(sourceRow, column, sourceParent)
.data(self.filterRole())
)
if value == self.filter_value:
return True
return False
def setFilterRegExp(self, filter):
self.filter_value = None
super().setFilterRegExp(filter)
class UI(QMainWindow):
def __init__(self):
super(UI, self).__init__()
uic.loadUi("tableview.ui", self)
self.show()
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('book.db')
db.open()
self.model = QtSql.QSqlTableModel(self)
self.model.setTable("card")
self.model.select()
self.tableView.setModel(self.model)
self.proxy = FilterProxyModel(self)
self.proxy.setSourceModel(self.model)
self.tableView.setModel(self.proxy)
self.model.select()
self.edit.clicked.connect(self.edit_items)
self.refresh.clicked.connect(self.refresh_table)
column_names = ["Name","Age","Gender"]
self.comboBox.addItems([x for x in column_names])
self.horizontalHeader = self.tableView.horizontalHeader()
self.horizontalHeader.sectionClicked.connect(
self.tableView_horizontalHeader_sectionClicked
)
self.lineEdit.textChanged.connect(self.lineEdit_textChanged)
def tableView_horizontalHeader_sectionClicked(self, logicalIndex):
menu = QtWidgets.QMenu(self)
values = []
for row in range(self.model.rowCount()):
value = self.model.index(row, logicalIndex).data(self.proxy.filterRole())
values.append(value)
action_all = QtWidgets.QAction("All", self)
action_all.setData(None)
menu.addAction(action_all)
menu.addSeparator()
for value in sorted(list(set(values))):
action = QtWidgets.QAction(str(value), self)
action.setData(value)
menu.addAction(action)
headerPos = self.tableView.mapToGlobal(self.horizontalHeader.pos())
posY = headerPos.y() + self.horizontalHeader.height()
posX = headerPos.x() + self.horizontalHeader.sectionPosition(logicalIndex)
action = menu.exec_(QtCore.QPoint(posX, posY))
if action is not None:
self.proxy.setFilterKeyColumn(logicalIndex)
self.proxy.filter_value = action.data()
def lineEdit_textChanged(self):
search = QtCore.QRegExp( self.lineEdit.text(),
QtCore.Qt.CaseInsensitive,
QtCore.QRegExp.RegExp
)
self.proxy.setFilterKeyColumn(self.comboBox.currentIndex() - 1)
self.proxy.setFilterRegExp(search)
def edit_items(self):
if not self.model.rowCount():
return
index = self.tableView.currentIndex()
if index.isValid():
row = index.row()
else:
row = 0
dialog = QtWidgets.QDialog()
dialog.setWindowTitle("Edit Window")
layout = QtWidgets.QVBoxLayout(dialog)
formLayout = QtWidgets.QFormLayout()
layout.addLayout(formLayout)
name_line = QtWidgets.QLineEdit(self.model.index(row, 0).data())
formLayout.addRow('Name', name_line)
name_line.setReadOnly(True)
age_edit = QtWidgets.QSpinBox()
formLayout.addRow('Age', age_edit)
age_edit.setFocus()
age_edit.setValue(self.model.index(row, 1).data())
genders = 'M', 'F'
gender_combo = QtWidgets.QComboBox()
formLayout.addRow('Gender', gender_combo)
gender_combo.addItems(genders)
gender = self.model.index(row, 2).data()
if gender and gender.upper() in genders:
gender_combo.setCurrentIndex(genders.index(gender.upper()))
else:
gender_combo.setCurrentIndex(-1)
updateButton = QtWidgets.QPushButton('Update')
layout.addWidget(updateButton)
updateButton.clicked.connect(dialog.accept)
if not dialog.exec_():
return
self.model.setData(self.model.index(row, 1), age_edit.value(),
QtCore.Qt.EditRole)
if gender_combo.currentIndex() >= 0:
self.model.setData(self.model.index(row, 2),
gender_combo.currentText(), QtCore.Qt.EditRole)
# submit all changes to the database
self.model.submitAll()
def refresh_table(self):
print("rsfersh")
This is working good Before filtering the columns with FilterProxyModel.
The problem is: Not getting exact row into "Edit Window", after filter the columns. For example its getting the row of db index row not from tableview.
Below is the reference Image.
As above image after filter, I want to edit 4th column("name4") but it is taking 1st column("name1"). How to edit required column after filtered.
The currentIndex method of QTableView returns a QModelIndex associated with the model established in the model, in this it is "self.proxy" and not with respect to "self.model". On the other hand, in these cases the task of mapping the columns is simplified using QDataWidgetMapper:
import sys
from PyQt5 import QtCore, QtWidgets, QtSql, uic
class FilterProxyModel(QtCore.QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self._filter_value = None
#property
def filter_value(self):
return self._filter_value
#filter_value.setter
def filter_value(self, value):
self._filter_value = value
self.invalidateFilter()
def filterAcceptsRow(self, sourceRow, sourceParent):
if self.filter_value is None:
return super().filterAcceptsRow(sourceRow, sourceParent)
if self.filterKeyColumn() >= 0:
value = (
self.sourceModel()
.index(sourceRow, self.filterKeyColumn(), sourceParent)
.data(self.filterRole())
)
return value == self.filter_value
for column in range(self.columnCount()):
value = (
self.sourceModel()
.index(sourceRow, column, sourceParent)
.data(self.filterRole())
)
if value == self.filter_value:
return True
return False
def setFilterRegExp(self, filter):
self.filter_value = None
super().setFilterRegExp(filter)
class UI(QtWidgets.QMainWindow):
def __init__(self):
super(UI, self).__init__()
uic.loadUi("tableview.ui", self)
self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("book.db")
db.open()
self.model = QtSql.QSqlTableModel(self)
self.model.setTable("card")
self.model.select()
self.proxy = FilterProxyModel(self)
self.proxy.setSourceModel(self.model)
self.tableView.setModel(self.proxy)
self.model.select()
self.edit.clicked.connect(self.edit_items)
self.refresh.clicked.connect(self.refresh_table)
r = self.model.record()
column_names = [r.field(i).name().title() for i in range(r.count())]
self.comboBox.addItems([x for x in column_names])
self.horizontalHeader = self.tableView.horizontalHeader()
self.horizontalHeader.sectionClicked.connect(
self.tableView_horizontalHeader_sectionClicked
)
self.lineEdit.textChanged.connect(self.lineEdit_textChanged)
def tableView_horizontalHeader_sectionClicked(self, logicalIndex):
menu = QtWidgets.QMenu(self)
values = []
for row in range(self.model.rowCount()):
value = self.model.index(row, logicalIndex).data(self.proxy.filterRole())
values.append(value)
action_all = QtWidgets.QAction("All", self)
action_all.setData(None)
menu.addAction(action_all)
menu.addSeparator()
for value in sorted(list(set(values))):
action = QtWidgets.QAction(str(value), self)
action.setData(value)
menu.addAction(action)
headerPos = self.tableView.mapToGlobal(self.horizontalHeader.pos())
posY = headerPos.y() + self.horizontalHeader.height()
posX = headerPos.x() + self.horizontalHeader.sectionPosition(logicalIndex)
action = menu.exec_(QtCore.QPoint(posX, posY))
if action is not None:
self.proxy.setFilterKeyColumn(logicalIndex)
self.proxy.filter_value = action.data()
def lineEdit_textChanged(self):
search = QtCore.QRegExp(
self.lineEdit.text(), QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp
)
self.proxy.setFilterKeyColumn(self.comboBox.currentIndex())
self.proxy.setFilterRegExp(search)
def edit_items(self):
if not self.model.rowCount():
return
index = self.tableView.currentIndex()
if index.isValid():
row = index.row()
else:
row = 0
name_line = QtWidgets.QLineEdit(readOnly=True)
age_edit = QtWidgets.QSpinBox()
gender_combo = QtWidgets.QComboBox()
genders = "M", "F"
gender_combo.addItems(genders)
updateButton = QtWidgets.QPushButton("Update")
mapper = QtWidgets.QDataWidgetMapper()
mapper.setSubmitPolicy(QtWidgets.QDataWidgetMapper.ManualSubmit)
mapper.setModel(self.tableView.model())
mapper.addMapping(name_line, 0)
mapper.addMapping(age_edit, 1)
mapper.addMapping(gender_combo, 2)
mapper.setCurrentIndex(row)
dialog = QtWidgets.QDialog()
dialog.setWindowTitle("Edit Window")
layout = QtWidgets.QVBoxLayout(dialog)
formLayout = QtWidgets.QFormLayout()
layout.addLayout(formLayout)
formLayout.addRow("Name", name_line)
formLayout.addRow("Age", age_edit)
formLayout.addRow("Gender", gender_combo)
layout.addWidget(updateButton)
updateButton.clicked.connect(dialog.accept)
if dialog.exec_():
mapper.submit()
def refresh_table(self):
print("refresh")
def main():
app = QtWidgets.QApplication(sys.argv)
w = UI()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

Fading on Tab Change in pyqt

i have a page containing two tabs.i want to add a fadeIn effect when i change the tabs.Is that possible?
import sys
from PyQt4.QtCore import QTimeLine
from PyQt4.QtGui import *
class FaderWidget(QWidget):
def __init__(self, old_widget, new_widget):
QWidget.__init__(self, new_widget)
self.old_pixmap = QPixmap(new_widget.size())
old_widget.render(self.old_pixmap)
self.pixmap_opacity = 1.0
self.timeline = QTimeLine()
self.timeline.valueChanged.connect(self.animate)
self.timeline.finished.connect(self.close)
self.timeline.setDuration(333)
self.timeline.start()
self.resize(new_widget.size())
self.show()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
painter.setOpacity(self.pixmap_opacity)
painter.drawPixmap(0, 0, self.old_pixmap)
painter.end()
def animate(self, value):
self.pixmap_opacity = 1.0 - value
self.repaint()
class StackedWidget(QStackedWidget):
def __init__(self, parent = None):
QStackedWidget.__init__(self, parent)
def setCurrentIndex(self, index):
self.fader_widget = FaderWidget(self.currentWidget(), self.widget(index))
QStackedWidget.setCurrentIndex(self, index)
def setPage1(self):
self.setCurrentIndex(0)
def setPage2(self):
self.setCurrentIndex(1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QWidget()
stack = StackedWidget()
stack.addWidget(QCalendarWidget())
editor = QTextEdit()
editor.setPlainText("Hello world! "*100)
stack.addWidget(editor)
page1Button = QPushButton("Page 1")
page2Button = QPushButton("Page 2")
page1Button.clicked.connect(stack.setPage1)
page2Button.clicked.connect(stack.setPage2)
layout = QGridLayout(window)
layout.addWidget(stack, 0, 0, 1, 2)
layout.addWidget(page1Button, 1, 0)
layout.addWidget(page2Button, 1, 1)
window.show()
sys.exit(app.exec_())
this is code that shows some fade effect but i m getting nothing from it and how it works and how to implement on tabs. it will be really appreciable if someone could help me implement it on tabs as well.
thanks in advance.
With the same logic as the code you show, each widget will be placed inside a QStackedWidget, where one of them will be the widget that will be displayed and the other will be the FaderWidget.
class FaderWidget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.pixmap_opacity = None
self.timeline = QTimeLine(333, self)
self.timeline.valueChanged.connect(self.animate)
self.timeline.finished.connect(self.close)
def start(self, old_widget, new_widget):
self.pixmap_opacity = 1.0
self.old_pixmap = QPixmap(new_widget.size())
old_widget.render(self.old_pixmap)
self.timeline.start()
self.resize(new_widget.size())
self.show()
def paintEvent(self, event):
if self.pixmap_opacity:
QWidget.paintEvent(self, event)
painter = QPainter(self)
painter.setOpacity(self.pixmap_opacity)
painter.drawPixmap(0, 0, self.old_pixmap)
def animate(self, value):
self.pixmap_opacity = 1.0 - value
self.update()
class FaderTabWidget(QTabWidget):
def __init__(self, parent=None):
QTabWidget.__init__(self, parent)
self.currentChanged.connect(self.onCurrentIndex)
self.last = -1
self.current = self.currentIndex()
def onCurrentIndex(self, index):
self.last = self.current
self.current = self.currentIndex()
if self.widget(self.last):
self.widget(self.last).setCurrentIndex(1)
old_widget = self.widget(self.last).widget(0)
current_widget = self.widget(self.current).widget(0)
fade = self.widget(self.current).widget(1)
fade.start(old_widget, current_widget)
def addTab(self, widget, text):
stack = QStackedWidget(self)
stack.addWidget(widget)
fade = FaderWidget(self)
fade.timeline.finished.connect(lambda: stack.setCurrentIndex(0))
stack.addWidget(fade)
stack.setCurrentIndex(0 if self.currentIndex() == -1 else 1)
QTabWidget.addTab(self, stack, text)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QWidget()
tabWidget = FaderTabWidget()
tabWidget.addTab(QCalendarWidget(), "Tab1")
editor = QTextEdit()
editor.setPlainText("Hello world! " * 100)
tabWidget.addTab(editor, "Tab2")
layout = QVBoxLayout(window)
layout.addWidget(tabWidget)
window.show()
sys.exit(app.exec_())

PyQT: adding to QAbstractItemModel using a button

I'm trying to implement a TreeView using QAbstractItemModel. I want to set up an empty model and then add an item to the model using a button.
This appears to be a lot more complex than I'd realised! I've modified a custom instance of the QAbstractItemModel example found in the Lib\site-packages\PyQt4\examples\itemviews\simpletreemodel\simpletreemodel.pyw.
Rather than setting up the model all at once, I want o build it incrementally.
When I click the button, I get the message showing that the process method is executing, but the model isn't updated.
Any pointers as to why it's not working would be greatly appreciated!
from PyQt4 import QtGui, QtCore
import sys
class myWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(500, 400)
#Tree Widget
self.treeView = QtGui.QTreeView(self)
#Model
self.model = TreeModel()
self.treeView.setModel(self.model)
# Button
self.button = QtGui.QPushButton(self)
self.button.setText('Add Item')
self.button.clicked.connect(self.process)
# Add to Layout
self.gridLayout = QtGui.QGridLayout(self)
self.gridLayout.addWidget(self.button,0,0)
self.gridLayout.addWidget(self.treeView,1,0)
def process(self):
print "here"
newItem = TreeItem(["bob","bob","bob"],self.model.rootItem)
self.model.rootItem.appendChild(newItem)
class TreeItem(object):
def __init__(self, data, parent=None):
self.parentItem = parent
self.itemData = data
self.childItems = []
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def columnCount(self):
return len(self.itemData)
def data(self, column):
try:
return self.itemData[column]
except IndexError:
return None
def parent(self):
return self.parentItem
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
class TreeModel(QtCore.QAbstractItemModel):
def __init__(self, parent=None):
super(TreeModel, self).__init__(parent)
self.rootItem = TreeItem(("Model", "Status","Location"))
def columnCount(self, parent):
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.rootItem.columnCount()
def data(self, index, role):
if not index.isValid():
return None
if role != QtCore.Qt.DisplayRole:
return None
item = index.internalPointer()
return item.data(index.column())
def flags(self, index):
if not index.isValid():
return QtCore.Qt.NoItemFlags
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.rootItem.data(section)
return None
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
parentItem = childItem.parent()
if parentItem == self.rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent):
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()
if __name__ == "__main__":
app = QtGui.QApplication.instance() # checks if QApplication already exists
if not app: # create QApplication if it doesnt exist
app = QtGui.QApplication(sys.argv)
# Window
window = myWindow()
window.show()
sys.exit(app.exec_())
Using a QStandardItemModel has worked a treat!
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(500, 400)
#Tree Widget
self.treeView = QTreeView()
#Model
self.model = QStandardItemModel()
self.treeView.setModel(self.model)
# Button
self.button = QPushButton()
self.button.setText('Add Item')
self.button.clicked.connect(self.addChildClick)
# Add to Layout
self.gridLayout = QGridLayout(self)
self.gridLayout.addWidget(self.button,0,0)
self.gridLayout.addWidget(self.treeView,1,0)
def addChildClick(self):
selection = self.treeView.selectedIndexes()
text = "bob"
item = QStandardItem(text)
# if nothing selected parent is model
if selection == []:
parent = self.model
else: # Otherwise parent is what is selected
s = selection[0] # Handling multiple selectons
parent = self.model.itemFromIndex(s)
parent.appendRow(item)
#cleanup
self.treeView.expandAll()
self.treeView.clearSelection()
if __name__ == "__main__":
app = QApplication.instance() # checks if QApplication already exists
if not app: # create QApplication if it doesnt exist
app = QApplication(sys.argv)
# Window
window = Window()
window.show()
app.exec_()

qtreeview root colored

I have a QTreeView with a colored background but I need to have also the root colored..
I'm not able to do so.
Someone can help me?
This is the code..
Thanks
from PyQt4 import QtGui, QtCore
HORIZONTAL_HEADERS = ("Surname", "Given Name")
class person_class(object):
def init(self, sname, fname, isMale):
self.sname = sname
self.fname = fname
self.isMale = isMale
class TreeItem(object):
def init(self, person, header, parentItem):
self.person = person
self.parentItem = parentItem
self.header = header
self.childItems = []
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def columnCount(self):
return 2
def data(self, column):
if self.person == None:
if column == 0:
return QtCore.QVariant(self.header)
if column == 1:
return QtCore.QVariant("")
else:
if column == 0:
return QtCore.QVariant(self.person.sname)
if column == 1:
return QtCore.QVariant(self.person.fname)
return QtCore.QVariant()
def parent(self):
return self.parentItem
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
class treeModel(QtCore.QAbstractItemModel):
def init(self, parent=None):
super(treeModel, self).init(parent)
self.people = []
for fname, sname, isMale in (("John","Brown", 1),
("Fred", "Bloggs", 1), ("Sue", "Smith", 0)):
person = person_class(sname, fname, isMale)
self.people.append(person)
self.rootItem = TreeItem(None, "ALL", None)
self.parents = {0 : self.rootItem}
self.setupModelData()
def columnCount(self, parent=None):
if parent and parent.isValid():
return parent.internalPointer().columnCount()
else:
return len(HORIZONTAL_HEADERS)
def data(self, index, role):
if not index.isValid():
return QtCore.QVariant()
item = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
return item.data(index.column())
if role == QtCore.Qt.UserRole:
if item:
return item.person
if role == QtCore.Qt.BackgroundRole :
return QtGui.QColor('pink')
return QtCore.QVariant()
#def headerData(self, column, orientation, role):
#if (orientation == QtCore.Qt.Horizontal and
#role == QtCore.Qt.DisplayRole):
#try:
#return QtCore.QVariant(HORIZONTAL_HEADERS[column])
#except IndexError:
#pass
#return QtCore.QVariant()
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
if not childItem:
return QtCore.QModelIndex()
parentItem = childItem.parent()
if parentItem == self.rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.column() > 0:
return 0
if not parent.isValid():
p_Item = self.rootItem
else:
p_Item = parent.internalPointer()
return p_Item.childCount()
def setupModelData(self):
for person in self.people:
if person.isMale:
sex = "MALES"
else:
sex = "FEMALES"
if not self.parents.has_key(sex):
newparent = TreeItem(None, sex, self.rootItem)
self.rootItem.appendChild(newparent)
self.parents[sex] = newparent
parentItem = self.parents[sex]
newItem = TreeItem(person, "", parentItem)
parentItem.appendChild(newItem)
if name == "main":
app = QtGui.QApplication([])
model = treeModel()
dialog = QtGui.QDialog()
dialog.setMinimumSize(300,150)
layout = QtGui.QVBoxLayout(dialog)
tv = QtGui.QTreeView(dialog)
tv.setModel(model)
layout.addWidget(tv)
dialog.exec_()
app.closeAllWindows()

Resources