为什么这个pyside代码不会更新它的小部件/视图?

时间:2014-06-15 15:36:00

标签: python qt pyside

我是pyside的新手,可能不太了解GUI库的概念。我对以下代码(python3.3)有一个特定的问题,我在其中创建了一个表的视图和一个按钮。按下按钮后,数据将添加到窗口小部件的日期,并且应重新绘制表格。但该表不会使用添加的内容自行更新。

我如何修复代码,以便在按下' Do_something'之后表格自动更新/重绘?按钮?

有关我的代码的其他建议,我将非常感谢!

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_()

1 个答案:

答案 0 :(得分:0)

在阅读了更多文档之后,事实证明在添加新数据行后,您需要发出rowsInserted信号。所以,以下就足够了:

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)