Python 为什么这个pyside代码不更新它的小部件/视图?
我是pyside的新手,可能不太了解GUI库的概念。我对下面的代码python3.3有一个特定的问题,我在其中创建了一个表视图和一个按钮。按下按钮后,数据将添加到小部件的日期中,并且应重新绘制表格。但该表不会使用添加的内容更新自身 我如何修复代码,使表在按下“Do_something”(做某事)按钮后自动更新/重画 对于我的代码的其他建议,我将非常感谢Python 为什么这个pyside代码不更新它的小部件/视图?,python,qt,pyside,Python,Qt,Pyside,我是pyside的新手,可能不太了解GUI库的概念。我对下面的代码python3.3有一个特定的问题,我在其中创建了一个表视图和一个按钮。按下按钮后,数据将添加到小部件的日期中,并且应重新绘制表格。但该表不会使用添加的内容更新自身 我如何修复代码,使表在按下“Do_something”(做某事)按钮后自动更新/重画 对于我的代码的其他建议,我将非常感谢 from PySide.QtCore import * from PySide.QtGui import * class MyWindow(Q
from PySide.QtCore import *
from PySide.QtGui import *
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
# this list represents the database
self.data_list = [
('John', 'Connor', 'terminated'),
('Buzz', 'Lightyea', 'animated')
]
self.header = ['name', 'lastname', 'extra']
# set basic window stuff
self.setGeometry(300, 200, 970, 450)
self.setWindowTitle("Main Stock Overview")
# add the model to the view
self.table_model = MyTableModel(self, self.data_list, self.header)
self.table_view = QTableView()
self.table_view.setModel(self.table_model)
# add the table to the layout
layout = QVBoxLayout(self)
layout.addWidget(self.table_view)
btn1 = QPushButton("Do_something", self)
btn1.clicked.connect(self.do_something)
# add some button to the layout
action_layout = QHBoxLayout(self)
action_layout.addStretch(1)
action_layout.addWidget(btn1)
layout.addLayout(action_layout)
self.setLayout(layout)
def do_something(self):
# update the 'database'
self.data_list.append(('Harry','Potter','wizated'))
print("data has been updated: ", self.data_list)
# required to be redrawn here
index1 = self.table_model.createIndex(0,0)
index2 = self.table_model.createIndex(self.table_model.rowCount(self)+1, self.table_model.columnCount(self))
self.table_model.dataChanged.emit(index1, index2)
class MyTableModel(QAbstractTableModel):
def __init__(self, parent, mylist, header, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.mylist = mylist
self.header = header
def rowCount(self, parent):
return len(self.mylist)
def columnCount(self, parent):
return len(self.mylist[0])
def data(self, index, role):
if not index.isValid():
return None
elif role != Qt.DisplayRole:
return None
return self.mylist[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.header[col]
return None
app = QApplication([])
win = MyWindow()
win.show()
app.exec_()
在多读一点文档之后,发现在添加新的数据行之后,您需要发出信号。因此,以下几点就足够了:
def do_something(self):
self.data_list.append(('Harry','Potter','wizated'))
newRow = len(self.data_list) - 1
self.table_model.rowsInserted.emit(QModelIndex(), newRow, newRow)
终于成功了!从文档中找到正确的方法要花我很多时间。谢谢