我最近从PyQt 5.7.0更新到5.7.1,并且在更新停止正常工作之前正常工作的代码。所以,我的代码总是错误的,但是PyQt5允许它工作,或者在PyQt 5.7.1中引入了一个bug。
我有一个自定义表视图,它使用从QAbstractTableModel继承的自定义模型继承自QTableView。将新行添加到模型时,它们在表视图中不可见。事实上,没有任何行可见。通过一些调试,我已经验证了行数在我的派生模型类中按预期发生了变化。
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import PyQt5.Qt
class JobTableModel(QAbstractTableModel):
def __init__(self, data, parent):
super(JobTableModel, self).__init__()
assert isinstance(parent, QTableView), "'parent' is not a QTableView object"
self._parent = parent
self._data = data
self._rows = 0
self._updateModel()
# end constructor
def updateRows(self, rows):
self.layoutAboutToBeChanged.emit()
self._rows = rows
self.layoutChanged.emit()
# end updateRows
def _updateModel(self):
# Only update rows that are visible to the user
# Note: self._parent is a QTableView
minRow = self._parent.rowAt(0)
if minRow >= 0:
maxRow = self._parent.rowAt(self._parent.height())
if maxRow < 0: maxRow = self._rows - 1
for row in range(minRow, maxRow + 1):
self.dataChanged.emit(self.index(row, 0), self.index(row, self.columnCount(None) - 1))
QTimer.singleShot(490, self._updateModel)
# end _updateModel
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return str(section)
#
# end headerData
def rowCount(self, modelIndex):
return self._rows
# end rowCount
def columnCount(self, modelIndex):
return 8 # always the same number of columns
# end columnCount
def data(self, index, role):
if not index.isValid(): return None
if role == Qt.DisplayRole: return '{0}, {1}'.format(index.row(), index.column())
return None
# end data
class JobTableView(QTableView):
def __init__(self, data, parent):
super(JobTableView, self).__init__(parent)
self.setModel(JobTableModel(data, self))
self.setAlternatingRowColors(True)
self.setWordWrap(False)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.verticalHeader().setVisible(False)
self.verticalHeader().setDefaultSectionSize(23)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
if __name__ == '__main__':
app = QApplication(sys.argv)
tv = JobTableView(None, None)
tv.show()
tv.model().updateRows(1)
app.exec_()
答案 0 :(得分:0)
我使用PyQt-5.7,PyQt-5.7.1和PyQt-5.7.2.dev1701131704(使用SIP-4.19.1.dev1701101411构建)运行测试用例。这个问题在PyQt-5.7.1中是可重现的,但在其他两个版本中没有。因此,正如评论中所建议的那样,PyQt-5.7.1中存在一个已在最新快照中修复的错误。