当点击QPushButton PyQT5 QTableView显示并在此之后立即消失

时间:2014-08-24 22:32:57

标签: pyqt

class FunituresModel(QAbstractItemModel):
    def __init__(self):
        super(FunituresModel, self).__init__()
        self.furnitures = []

    def set_furnitures(self, furnitures):
        self.beginResetModel()
        self.furnitures = furnitures
        self.endResetModel()

    def rowCount(self, parent=QModelIndex()):
        return len(self.furnitures)

    def columnCount(self, parent=QModelIndex()):
        return 3

    def data(self, index, role):
        if not self.hasIndex(index.row(), index.column()) or role != Qt.DisplayRole:
            return QVariant()

        furniture = self.furnitures[index.row()]
        if index.column() == 0:
            return furniture.get_name()
        elif index.column() == 1:
            return furniture.get_quality()
        elif index.column() == 2:
            return furniture.get_room_number()

        return QVariant()

    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole:
            return QVariant()
        if orientation == Qt.Vertical:
            if not self.is_valid_row_index(section):
                return QVariant()
            else:
                return section + 1
        if orientation == Qt.Horizontal:
            if not self.is_valid_column_index(section):
                return QVariant()
            else:
                if section == 0:
                    return "Room Number"
                elif section == 1:
                    return "Name"
                elif section == 2:
                    return "Quality"
        return QVariant()

    def index(self, row, column, parent):
        if self.is_valid_row_index(row) and self.is_valid_column_index(column):
            return self.createIndex(row, column)
        else:
            return QModelIndex()

    def is_valid_row_index(self, row_index):
        return 0 <= row_index and row_index < self.rowCount()

    def is_valid_column_index(self, column_index):
        return 0 <= column_index and column_index < self.columnCount()

    def parent(self, child):
        return QModelIndex()



def show_furniture_table(furnitures):
    table = QTableView()
    table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
    model = FunituresModel()
    model.set_furnitures(furnitures)
    table.setModel(model)
    table.show()

这真的很奇怪,因为在主函数中使用show_furniture_table中的代码时它可以工作。但是当我的形式选择组合框家具并点击时,它立即显示。而且当它显示一段时间时,似乎qtableview中没有信息。任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

table的生命周期与show_furniture_table函数相关联。当此函数返回时,table超出范围并被Python的垃圾收集机制删除。如果您希望它存在于函数范围之外,则需要从table返回对show_furniture_table的引用。