Display GIF while data is loading from database with pyqt5 - python

how i can show a loading GIF image or a Qlabel update while i load data from database with QAbstractTableModel.i am new in pyqt5 and i tried it from last week but didn't understand how i can do that .
there are many example i found in stackoverflow but i really cannot deal with Qthread.i don't want to use timer for it as i can see in many examples are using qtimer. loading gif is automatically close while loading completed in table.
can anyone please show me how to do this and describes all things.
from PyQt5 import QtCore, QtWidgets
import pandas as pd
import numpy as np
import pyodbc
class NumpyArrayModel(QtCore.QAbstractTableModel):
def __init__(self, array, headers, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent=parent)
self._array = array
self._headers = headers
self.r, self.c = np.shape(self.array)
#property
def array(self):
return self._array
#property
def headers(self):
return self._headers
def rowCount(self, parent=QtCore.QModelIndex()):
return self.r
def columnCount(self, parent=QtCore.QModelIndex()):
return self.c
def headerData(self, p_int, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
if p_int < len(self.headers):
return self.headers[p_int]
elif orientation == QtCore.Qt.Vertical:
return p_int + 1
return
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
row = index.row()
column = index.column()
if row < 0 or row >= self.rowCount():
return None
if column < 0 or column >= self.columnCount():
return None
if role == QtCore.Qt.DisplayRole:
return str(self.array[row, column])
return None
def setData(self, index, value, role):
if not index.isValid():
return False
if role != QtCore.Qt.EditRole:
return False
row = index.row()
column = index.column()
if row < 0 or row >= self.rowCount():
return False
if column < 0 or column >= self.columnCount():
return False
self.array.values[row][column] = value
self.dataChanged.emit(index, index)
return True
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent=None)
vLayout = QtWidgets.QVBoxLayout(self)
hLayout = QtWidgets.QHBoxLayout()
self.pathLE = QtWidgets.QLabel(self)
hLayout.addWidget(self.pathLE)
self.loadBtn = QtWidgets.QPushButton("Load data", self)
hLayout.addWidget(self.loadBtn)
vLayout.addLayout(hLayout)
self.pandasTv = QtWidgets.QTableView(self)
vLayout.addWidget(self.pandasTv)
self.loadBtn.clicked.connect(self.loadFile)
self.pandasTv.setSortingEnabled(True)
def loadFile(self):
self.pathLE.setText("Loading data")
server = '190.11.71.09'
database = ''
username = 'Admin'
passwd = ''
conn= pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' +
server+';DATABASE='+database+';UID='+username+';PWD=' + passwd)
query="select * from database.dbo.tableName(nolock)"
df = pd.read_sql_query(query, conn)
array = np.array(df.values)
headers = df.columns.tolist()
model = NumpyArrayModel(array, headers)
self.pandasTv.setModel(model)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

Learn how to display a GIF image.
Then learn how to trigger an action via a button.
Do not fall into the typical pit by implementing your action to
display the GIF
load the data
hide the GIF
as this ties down the one thread that triggered your action. This one thread is crucial to keep the UI updating.
So what you need to do when the button gets pressed:
Spawn a new thread to execute some code
In the new thread the code to execute contains the above statements:
show GIF
load data
hide GIF (even if data loading fails)
For showing, hiding and finally rendering the loaded data you will have to look out because now you try to modify the UI from another thread - this will need some kind of treatment. BTW this behaviour is not specific to Qt. You will find similar things in Java AWT and Swing.

Related

Can I re-count the verticalHeader when I go to hide a row of QTableView?

I'll use some filtering criteria to hide some of the rows, I want the verticalHeader to redisplay the sequence number:
from PyQt5 import QtWidgets
from PyQt5 import QtGui
class MyQTableView(QtWidgets.QTableView):
def __init__(self, parent=None):
super(MyQTableView, self).__init__(parent)
self.model = QtGui.QStandardItemModel()
self.setModel(self.model)
self.init_data(['title'], [('a',), ('b',), ('c',)])
def init_data(self, headers, datas):
self.model.setHorizontalHeaderLabels(headers)
for row, rows in enumerate(datas):
for column, data in enumerate(rows):
item = QtGui.QStandardItem(f'{data}')
self.model.setItem(row, column, item)
if row == 1:
#To hide a row
self.setRowHidden(1, True)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
table = MyQTableView()
table.show()
sys.exit(app.exec_())
The actual QTableView is as follows:
title
1 a
3 c
The expected QTableView as:
title
1 a
2 c
In this case instead of hiding rows it is better to use a QSortFilterProxyModel where it overrides the headerData so that it does not depend on the sourceModel and implementing the custom filter.
class FilterProxyModel(QtCore.QSortFilterProxyModel):
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return section + 1
return super().headerData(section, orientation, role)
def filterAcceptsRow(self, row, parent):
if row == 1:
return False
return True
class MyQTableView(QtWidgets.QTableView):
def __init__(self, parent=None):
super(MyQTableView, self).__init__(parent)
self.model = QtGui.QStandardItemModel()
self.proxy_model = FilterProxyModel()
self.proxy_model.setSourceModel(self.model)
self.setModel(self.proxy_model)
self.init_data(["title"], [("a",), ("b",), ("c",)])
def init_data(self, headers, datas):
self.model.setHorizontalHeaderLabels(headers)
for row, rows in enumerate(datas):
for column, data in enumerate(rows):
item = QtGui.QStandardItem(f"{data}")
self.model.setItem(row, column, item)

Why can I emit dataChanged(), but not layoutChanged() in a PySide2 table model?

I am new to Qt. Currently I am trying to learn how to update a table model from a different thread and then how to get an immediate display update for it. I read the documentation and found the dataChanged() and layoutChanged() signals. While dataChanged() works fine, any attempt to emit layoutChanged() fails with:
'QObject::connect: Cannot queue arguments of type 'QList<QPersistentModelIndex>' (Make sure 'QList<QPersistentModelIndex>' is registered using qRegisterMetaType().)
Searching for this particular error didn't give me anything that I could turn into working code. I am not using any QList or QPersistentModelIndex explicitly, but of course that can be implicitly used due to the constructs that I chose.
What am I doing wrong?
class TimedModel(QtCore.QAbstractTableModel):
def __init__(self, table, view):
super(TimedModel, self).__init__()
self.table = table
self.view = view
self.setHeaderData(0, Qt.Horizontal, Qt.AlignLeft, Qt.TextAlignmentRole)
self.rows = 6
self.columns = 4
self.step = 5
self.timer = Thread(
name = "Timer",
target = self.tableTimer,
daemon = True)
self.timer.start()
self.random = Random()
self.updated = set()
#staticmethod
def encode(row, column):
return row << 32 | column
def data(self, index, role):
if role == Qt.DisplayRole or role == Qt.EditRole:
return f'Data-{index.row()}-{index.column()}'
if role == Qt.ForegroundRole:
encoded = TimedModel.encode(index.row(), index.column())
return QBrush(Qt.red if encoded in self.updated else Qt.black)
return None
def rowCount(self, index):
return self.rows
def columnCount(self, index):
return self.columns
def headerData(self, col, orientation, role):
if orientation == Qt.Vertical:
# Vertical
return super().headerData(col, orientation, role)
# Horizontal
if not 0 <= col < self.columns:
return None
if role == Qt.DisplayRole:
return f'Data-{col}'
if role == Qt.TextAlignmentRole:
return int(Qt.AlignLeft | Qt.AlignVCenter)
return super().headerData(col, orientation, role)
def tableTimer(self):
while True:
time.sleep(5.0)
randomRow = self.random.randint(0, self.rows)
randomColumn = self.random.randint(0, self.columns)
encodedRandom = TimedModel.encode(randomRow, randomColumn)
if encodedRandom in self.updated:
self.updated.remove(encodedRandom)
else:
self.updated.add(encodedRandom)
updatedIndex = self.createIndex(randomRow, randomColumn)
self.dataChanged.emit(updatedIndex, updatedIndex)
'''this here does not work:'''
self.layoutAboutToBeChanged.emit()
self.rows += self.step
self.layoutChanged.emit()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.timedTable = QTableView()
self.model = TimedModel(self.timedTable, self)
self.timedTable.setModel(self.model)
headerView = self.timedTable.horizontalHeader()
headerView.setStretchLastSection(True)
self.setCentralWidget(self.timedTable)
self.setGeometry(300, 300, 1000, 600)
self.setWindowTitle('Timed Table')
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.name = "Timed Table Application"
window = MainWindow()
window.show()
app.exec_()
The following code:
self.layoutAboutToBeChanged.emit()
self.rows += self.step
self.layoutChanged.emit()
create new model elements that have QPersistentModelIndex associated that are not thread-safe and that Qt monitors its creation to warn its misuse as in this case since modifying that element is unsafe since it implies modifying the GUI from another thread (Read here for more information).
So you see that message warning that what you are trying to do is unsafe.
Instead dataChanged only emits a signal, does not create any element belonging to Qt, and you have been lucky that the modification of "self.updated" has not generated bottlenecks since you modify a property that belongs to the main thread from a secondary thread without use guards as mutexes.
Qt points out that the GUI and the elements that the GUI uses should only be updated in the GUI thread, and if you want to modify the GUI with information from another thread, then you must send that information, for example, using the signals that are thread- safe:
import random
import sys
import threading
import time
from PySide2 import QtCore, QtGui, QtWidgets
class TimedModel(QtCore.QAbstractTableModel):
random_signal = QtCore.Signal(object)
def __init__(self, table, view):
super(TimedModel, self).__init__()
self.table = table
self.view = view
self.setHeaderData(
0, QtCore.Qt.Horizontal, QtCore.Qt.AlignLeft, QtCore.Qt.TextAlignmentRole
)
self.rows = 6
self.columns = 4
self.step = 5
self.updated = set()
self.random_signal.connect(self.random_slot)
self.timer = threading.Thread(name="Timer", target=self.tableTimer, daemon=True)
self.timer.start()
#staticmethod
def encode(row, column):
return row << 32 | column
def data(self, index, role):
if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
return f"Data-{index.row()}-{index.column()}"
if role == QtCore.Qt.ForegroundRole:
encoded = TimedModel.encode(index.row(), index.column())
return QtGui.QBrush(
QtCore.Qt.red if encoded in self.updated else QtCore.Qt.black
)
return None
def rowCount(self, index):
return self.rows
def columnCount(self, index):
return self.columns
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Vertical:
# Vertical
return super().headerData(col, orientation, role)
# Horizontal
if not 0 <= col < self.columns:
return None
if role == QtCore.Qt.DisplayRole:
return f"Data-{col}"
if role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter
return super().headerData(col, orientation, role)
def tableTimer(self):
while True:
time.sleep(5.0)
randomRow = random.randint(0, self.rows)
randomColumn = random.randint(0, self.columns)
encodedRandom = TimedModel.encode(randomRow, randomColumn)
self.random_signal.emit(encodedRandom)
#QtCore.Slot(object)
def random_slot(self, encodedRandom):
if encodedRandom in self.updated:
self.updated.remove(encodedRandom)
else:
self.updated.add(encodedRandom)
self.layoutAboutToBeChanged.emit()
self.rows += self.step
self.layoutChanged.emit()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.timedTable = QtWidgets.QTableView()
self.model = TimedModel(self.timedTable, self)
self.timedTable.setModel(self.model)
headerView = self.timedTable.horizontalHeader()
headerView.setStretchLastSection(True)
self.setCentralWidget(self.timedTable)
self.setGeometry(300, 300, 1000, 600)
self.setWindowTitle("Timed Table")
self.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.name = "Timed Table Application"
window = MainWindow()
window.show()
app.exec_()

Catch ESC Key When Editing QTableView

Having trouble trying to figure out how to catch a row in a QTableView that's being edited has been canceled. For example, if I am editing a newly inserted row in a QTableView and the ESC, up/down arrows keys have been pressed, I need to remove the row because (in my mind) has been cancelled. Also holds true if the user clicks away from the row. I can't really post any code as I have no idea how to implement something like this. Any ideas?
I have a an example of, what I believe, is what you want (at least for key pressed issue). From there you can do something similar for the clicking issue.
My solution uses a custom QItemDelegate that overrides the eventFilter method. Also it uses a naive model (because you want to use QTableView), the use of the layoutChanged signal on the model is due to functionality of the example, read the docs for more suitable add/delete data features according to your needs.
Hope it helps.
The sample ui:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui',
# licensing of 'test.ui' applies.
#
# Created: Wed Nov 7 16:10:12 2018
# by: pyside2-uic running on PySide2 5.11.0
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Test(object):
def setupUi(self, Test):
Test.setObjectName("Test")
Test.resize(538, 234)
self.horizontalLayout = QtWidgets.QHBoxLayout(Test)
self.horizontalLayout.setObjectName("horizontalLayout")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.tableView = QtWidgets.QTableView(Test)
self.tableView.setObjectName("tableView")
self.gridLayout.addWidget(self.tableView, 0, 0, 1, 1)
self.addRow = QtWidgets.QPushButton(Test)
self.addRow.setObjectName("addRow")
self.gridLayout.addWidget(self.addRow, 0, 1, 1, 1)
self.horizontalLayout.addLayout(self.gridLayout)
self.retranslateUi(Test)
QtCore.QMetaObject.connectSlotsByName(Test)
def retranslateUi(self, Test):
Test.setWindowTitle(QtWidgets.QApplication.translate("Test", "Dialog", None, -1))
self.addRow.setText(QtWidgets.QApplication.translate("Test", "add row", None, -1))
The actual classes involved (I use PySide2):
from PySide2 import QtWidgets, QtCore, QtGui
from _test import Ui_Test
class MyDialog(QtWidgets.QDialog):
def __init__(self, parent = None):
super(MyDialog, self).__init__(parent = parent)
self.ui = Ui_Test()
self.ui.setupUi(self)
self._model = MyModel([["first row 1 col", "first row 2"],["second row 1", "second row 2"]])
self.ui.tableView.setModel(self._model)
self.ui.addRow.clicked.connect(self._model.addRow)
self.ui.tableView.setItemDelegate(MyDelegate(self.ui.tableView))
# this is crucial: we need to be sure that the selection is single on the view
self.ui.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectItems)
self.ui.tableView.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
class MyModel(QtCore.QAbstractTableModel):
def __init__(self, table_data = None, parent = None):
super(MyModel, self).__init__(parent = parent)
if not table_data: self._data = []
self._data = table_data
def rowCount(self, parent = None):
return len(self._data)
def columnCount(self, parent = None):
return 2
def addRow(self):
self._data.append(["new item", "new item"])
self.layoutChanged.emit()
def removeRow(self, row):
if 0 <= row < self.rowCount():
del self._data[row]
self.layoutChanged.emit()
def data(self, index, role = QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
row = index.row()
col = index.column()
return self._data[row][col]
def setData(self, index, value, role = QtCore.Qt.EditRole):
if index.isValid():
if role == QtCore.Qt.EditRole:
row = index.row()
col = index.column()
self._data[row][col] = str(value)
return True
else:
return False
else:
return False
def flags(self, index):
return QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled
class MyDelegate(QtWidgets.QItemDelegate):
def __init__(self, parent = None):
super(MyDelegate, self).__init__(parent)
self.view = parent
def eventFilter(self, editor, event):
# there is a lot of checking in order to identify the desired situation
# and avoid errors
if isinstance(event, QtGui.QKeyEvent):
if event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Escape:
# we should have a list here of length one (due to selection restrictions on the view)
index = self.view.selectedIndexes()
if index:
if index[0].isValid():
row = index[0].row()
self.view.model().removeRow(row)
return super(MyDelegate, self).eventFilter(editor, event)
if __name__ == '__main__':
app = QtWidgets.QApplication()
diag = MyDialog()
diag.show()
app.exec_()

Adjust the size (width/height) of a custom QTableWidget

I need a QTableWidget based on a QTabelModel and QTableView with some buttons added above the table. See the following figure:
The width of the QTableWidget should be adjusted so that it is not smaller than a reasonable minimum and not extend beyond the buttons above it; in particular, the size of the columns 1, 2, and 4 should be adjusted to their contents, and the 3rd column, Aberrations, should be expanded to fill in the gap on the right side. I'd like to know how to do this in code.
The following is a minimal example of the code I use for the custom QTableWidget (PyQt5, Python3):
from PyQt5 import QtGui, QtCore, QtWidgets
import numpy as np
#-- Table Model
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None, *args):
super(MyTableModel, self).__init__(parent)
# table data
self.table_data = data
self.rows_nr, self.columns_nr = data.shape
# vertical & horizontal header labels
self.hheaders = ["Head-{}".format(i) for i in range(self.columns_nr)]
self.vheaders = ["Row-{}".format(i) for i in range(self.rows_nr)]
# nr of rows
def rowCount(self, parent):
return self.rows_nr
# nr of columns
def columnCount(self, parent):
return self.columns_nr
# row and column headers
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.hheaders[section]
#END if
#ELSE:
return QtCore.QVariant()
# display table contents
def data(self, index, role=QtCore.Qt.DisplayRole):
r_ = index.row()
c_ = index.column()
if role == QtCore.Qt.DisplayRole:
return "{}".format(data[r_, c_])
#ELSE:
return QtCore.QVariant()
# set data
def setData(self, index, value, role):
r_ = index.row()
c_ = index.column()
# editable fields
if role == QtCore.Qt.EditRole:
# interprete values
self.table_data[r_,c_] = str(value)
return True
# view/edit flags
def flags(self, index):
r_ = index.row()
c_ = index.column()
return QtCore.Qt.ItemIsEnabled
class MyTableWidget(QtWidgets.QWidget):
def __init__(self, data, *args):
super(MyTableWidget, self).__init__(*args)
#-- table model
tablemodel = MyTableModel(data=data, parent=self)
#-- table view
tableview = QtWidgets.QTableView()
tableview.setModel(tablemodel)
tableview.verticalHeader().hide() # hide vertical/row headers
# size policy
tableview.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
tableview.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
#-- layouts
#--- buttons
button_hlayout = QtWidgets.QHBoxLayout()
button_hlayout.addWidget(QtWidgets.QPushButton("Button 1"))
button_hlayout.addWidget(QtWidgets.QPushButton("Button 2"))
button_hlayout.addWidget(QtWidgets.QPushButton("Button 3"))
#--- table
table_layout = QtWidgets.QVBoxLayout()
table_layout.addLayout(button_hlayout)
table_layout.addWidget(tableview)
self.setLayout(table_layout)
#----------------------------------------
#-- produce sample data
data = np.empty(shape=(3,4), dtype=np.object)
for r in range(3):
for c in range(4):
data[r,c] = str(list(range((r+1) * (c+1))))
app = QtWidgets.QApplication([""])
w = MyTableWidget(data=data)
w.show()
app.exec_()
void QHeaderView::setSectionResizeMode(int logicalIndex, QHeaderView::ResizeMode mode)
Sets the constraints on how the section specified by logicalIndex in the header can be resized to those described by the given mode. The logical index should exist at the time this function is called.
from PyQt5 import QtGui, QtCore, QtWidgets
import numpy as np
#-- Table Model
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None, *args):
super(MyTableModel, self).__init__(parent)
# table data
self.table_data = data
self.rows_nr, self.columns_nr = data.shape
# vertical & horizontal header labels
self.hheaders = ["Head-{}".format(i) for i in range(self.columns_nr)]
self.vheaders = ["Row-{}".format(i) for i in range(self.rows_nr)]
# nr of rows
def rowCount(self, parent):
return self.rows_nr
# nr of columns
def columnCount(self, parent):
return self.columns_nr
# row and column headers
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.hheaders[section]
#END if
#ELSE:
return QtCore.QVariant()
# display table contents
def data(self, index, role=QtCore.Qt.DisplayRole):
r_ = index.row()
c_ = index.column()
if role == QtCore.Qt.DisplayRole:
return "{}".format(data[r_, c_])
#ELSE:
return QtCore.QVariant()
# set data
def setData(self, index, value, role):
r_ = index.row()
c_ = index.column()
# editable fields
if role == QtCore.Qt.EditRole:
# interprete values
self.table_data[r_,c_] = str(value)
return True
# view/edit flags
def flags(self, index):
r_ = index.row()
c_ = index.column()
return QtCore.Qt.ItemIsEnabled
class MyTableWidget(QtWidgets.QWidget):
def __init__(self, data, *args):
super(MyTableWidget, self).__init__(*args)
#-- table model
tablemodel = MyTableModel(data=data, parent=self)
#-- table view
tableview = QtWidgets.QTableView()
tableview.setModel(tablemodel)
tableview.verticalHeader().hide() # hide vertical/row headers
#-- +++
tableview.setAlternatingRowColors(True)
tableview.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
tableview.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
tableview.horizontalHeader().setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
tableview.horizontalHeader().setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
# size policy
tableview.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
#tableview.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) # ---
tableview.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)# +++
#-- layouts
#--- buttons
button_hlayout = QtWidgets.QHBoxLayout()
button_hlayout.addWidget(QtWidgets.QPushButton("Button 1"))
button_hlayout.addWidget(QtWidgets.QPushButton("Button 2"))
button_hlayout.addWidget(QtWidgets.QPushButton("Button 3"))
#--- table
table_layout = QtWidgets.QVBoxLayout()
table_layout.addLayout(button_hlayout)
table_layout.addWidget(tableview)
self.setLayout(table_layout)
#----------------------------------------
#-- produce sample data
data = np.empty(shape=(3,4), dtype=np.object)
for r in range(3):
for c in range(4):
data[r,c] = str(list(range((r+1) * (c+1))))
app = QtWidgets.QApplication([""])
w = MyTableWidget(data=data)
w.show()
app.exec_()
In the code above, tableview.horizontalHeader().SetSectionResizeMode(QtWidgets.QHeaderView.Stretch) applies the Stretch mode to all columns, and the remaining 3 operators set the corresponding columns to the ResizeToContents mode.
The resizing behaviour of the widget window is determined by setSizePolicy method. In this case, the policy can be also tableview.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum), which allows the user to enlarge or shrink the widget window.

Unexpected padding pyqt in qtableview cell

I'm trying to create a custom TableModel class for QTableView. The cells containing 1 as data must have red outlining. Outlining is made by returning a pixmap (with red borders and text drawn on top) from TableModel instead of returning a simple string.
The problem is in the unexpected padding of the pixmap, which I return as DecorationRole. I checked if the pixmap is drawn correctly (and it actually is 21x21 px with well done outlining, without padding, just as planned) right before the return pixmap line.
Here is the right drawn pixmap, which was saved just before the return from TableModel:
Eventually, something shifts the returned pixmap by exactly 3px from the left border of the QTableView cell. I didn't set any padding in QtDesigner for the QTableView and didn't change it later in my code. I also tried to manually set up padding to zero using stylesheet, but it gave no different result.
Any ideas how to fix it? Thank you.
Here is the sample of my TableModel:
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, topology=None):
super().__init__()
...
# Hardcode cell size and path to rectangle image
self.cell_width, self.cell_height = 21, 21
self.fpath_red_rect = './path/to/red_rect.png'
def rowCount(self, parent=QtCore.QModelIndex()):
return self.data.shape[0]
def columnCount(self, parent=QtCore.QModelIndex()):
return self.data.shape[1]
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
...
def size(self):
return QtCore.QSize((self.columnCount() + 1) * self.cell_width,
(self.rowCount() + 1) * self.cell_height)
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return QtCore.QVariant()
i = index.row()
j = index.column()
if role == QtCore.Qt.DisplayRole:
if self.data[i, j] == 0: # empty
return ''
elif self.data[i, j] == 1: # cell with red rectangle
# the text will be drawn on pixmap manually later
return None
else:
return '{0}'.format(self.data[i, j]) # display default data
if role == QtCore.Qt.DecorationRole:
# Create pixmap, draw the rectangle on it and then draw text on top
pixmap = QtGui.QPixmap(self.cell_width, self.cell_height)
image = QtGui.QImage(self.fpath_red_rect).scaled(self.cell_width, self.cell_height)
painter = QtGui.QPainter(pixmap)
painter.drawImage(pixmap.rect().topLeft(), image)
painter.drawText(pixmap.rect(), QtCore.Qt.AlignCenter, '{0}'.format(self.data[i, j]))
painter.end()
# If we save the pixmap to PNG image here (see the link above),
# we get the expected 21 x 21 px image, with nice
# and properly drawn rectangle and centered text.
# But something goes wrong after returning
return pixmap
if role == QtCore.Qt.BackgroundRole:
return QtGui.QBrush(self.getQtColor(self.data[i, j]))
if role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
return QtCore.QVariant()
DecorationRole is used to draw the icon for that reason you observe the displacement, in your case you should not use that role, besides the painting task should not be done in the model since he only has to provide the data, if you want to modify the drawing a better option is use a delegate as I show below:
import sys
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
ValueRole = QtCore.Qt.UserRole + 1
max_val = 4
colors = [QtGui.QColor(*np.random.randint(255, size=3)) for i in range(max_val)]
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.data = np.random.randint(max_val, size=(10, 10))
def rowCount(self, parent=QtCore.QModelIndex()):
return self.data.shape[0]
def columnCount(self, parent=QtCore.QModelIndex()):
return self.data.shape[1]
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return QtCore.QVariant()
i = index.row()
j = index.column()
val = self.data[i, j]
if role == QtCore.Qt.DisplayRole:
return str(val)
elif role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
elif role == QtCore.Qt.BackgroundRole:
return colors[val]
if role == ValueRole:
return val
return QtCore.QVariant()
class Delegate(QtWidgets.QStyledItemDelegate):
def paint(self, painter, option, index):
QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
if index.data(ValueRole) == 1:
painter.save()
pen = painter.pen()
pen.setColor(QtCore.Qt.red)
painter.setPen(pen)
r = QtCore.QRect(option.rect)
r.adjust(0, 0, -pen.width(), -pen.width())
painter.drawRect(r)
painter.restore()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QTableView()
w.setItemDelegate(Delegate(w))
model = TableModel()
w.setModel(model)
w.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
w.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
for i in range(model.rowCount()):
w.verticalHeader().resizeSection(i, 21)
for j in range(model.columnCount()):
w.horizontalHeader().resizeSection(j, 21)
w.show()
sys.exit(app.exec_())

Categories