QTableView在使用pandas向数据插入行之后意外地左移

2024-04-19 23:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

----问题看起来如何----

enter image description here

在我点击了录制按钮之后,它变成了这个

enter image description here

如您所见,表格只是向左移动,隐藏了垂直标题。你知道吗

----相关代码----

我的tableivew被称为tableviewtransation,它使用模型以pandas的数据帧格式链接到数据。下面是我如何在QMainWindow__init__函数中将它们连接在一起的。你知道吗

    self.data = pd.read_csv('transactions.txt', sep='\t', header=None)
    self.data.columns = ["Name", "Price", "Action"]
    self.model = PandasModel(self.data)
    self.tableViewTransaction.setModel(self.model)

这是我的TableView模型

class PandasModel(QtCore.QAbstractTableModel): 
    def __init__(self, df = pd.DataFrame(), parent=None): 
        QtCore.QAbstractTableModel.__init__(self, parent=parent)
        self._df = df

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            try:
                return self._df.columns.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()
        elif orientation == QtCore.Qt.Vertical:
            try:
                # return self.df.index.tolist()
                return self._df.index.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if not index.isValid():
            return QtCore.QVariant()

        return QtCore.QVariant(str(self._df.ix[index.row(), index.column()]))

    def setData(self, index, value, role):
        row = self._df.index[index.row()]
        col = self._df.columns[index.column()]
        if hasattr(value, 'toPyObject'):
            # PyQt4 gets a QVariant
            value = value.toPyObject()
        else:
            # PySide gets an unicode
            dtype = self._df[col].dtype
            if dtype != object:
                value = None if value == '' else dtype.type(value)
        self._df.set_value(row, col, value)
        return True

    def rowCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.index)

    def columnCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.columns)

    def sort(self, column, order):
        colname = self._df.columns.tolist()[column]
        self.layoutChanged.emit()
        self._df.sort_values(colname, ascending= order == QtCore.Qt.AscendingOrder, inplace=True)
        self._df.reset_index(inplace=True, drop=True)
        self.layoutChanged.emit()

当按下录制按钮时,调用以下函数:

    def recordTransaction(self):
        name = self.comboBoxStock.currentText()
        price = self.lineEditMoney.text()
        action = self.comboBoxAction.currentText()

        self.data.loc[len(self.data.index)] = [name, price, action]
        self.tableViewTransaction.model().layoutChanged.emit()

我知道这里的名称、价格、操作存储的是正确的信息,即上面例子中的“stock1”、“2”、“Buy”。你知道吗

----完整代码----

https://drive.google.com/file/d/1rU66yLqlQu0bTdINkSWxJe2E_OdMtS0i/view?usp=sharing

使用方法: 首先解压,然后使用python3运行股票模拟价格. 在mac上,当您使用终端进入Stock Sim目录时,只需运行python3 StockSim.py。确保首先安装了python3和pyqt5。你知道吗

----------------------你知道吗

我只想让桌面视图不要向左移动,如果您能提供任何帮助,我将不胜感激!你知道吗


Tags: columnsselfdfdataindexreturnifvalue