You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSV填充QTable?点击按钮无响应求解决(附代码)

问题排查与修复方案:PyQt4 CSV读写按钮无响应

我一眼就看到了导致按钮点击无反应的核心问题——你的两个按钮槽函数定义在了MyWindow类的外部!Qt的信号槽机制需要槽函数是类的成员方法,不然按钮点击后根本找不到对应的执行逻辑,自然没任何反应。除此之外,我还帮你调整了文件读写的兼容性问题,并添加了错误处理,让代码更健壮。

修复后的完整代码

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import csv
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, fileName, parent=None):
        super(MyWindow, self).__init__(parent)
        self.fileName = fileName
        self.model = QtGui.QStandardItemModel(self)
        self.tableView = QtGui.QTableView(self)
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)

        self.pushButtonLoad = QtGui.QPushButton(self)
        self.pushButtonLoad.setText("Load Csv File!")
        self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)

        self.pushButtonWrite = QtGui.QPushButton(self)
        self.pushButtonWrite.setText("Write Csv File!")
        self.pushButtonWrite.clicked.connect(self.on_pushButtonWrite_clicked)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.tableView)
        self.layoutVertical.addWidget(self.pushButtonLoad)
        self.layoutVertical.addWidget(self.pushButtonWrite)

    def loadCsv(self, fileName):
        try:
            with open(fileName, "rb") as fileInput:
                for row in csv.reader(fileInput):
                    items = [
                        QtGui.QStandardItem(field.decode('utf-8') if isinstance(field, str) else field)
                        for field in row
                    ]
                    self.model.appendRow(items)
        except Exception as e:
            QtGui.QMessageBox.warning(self, "加载失败", f"无法读取文件:{str(e)}")

    def writeCsv(self, fileName):
        try:
            with open(fileName, "wb") as fileOutput:
                writer = csv.writer(fileOutput)
                for rowNumber in range(self.model.rowCount()):
                    fields = []
                    for columnNumber in range(self.model.columnCount()):
                        data = self.model.data(
                            self.model.index(rowNumber, columnNumber),
                            QtCore.Qt.DisplayRole
                        )
                        # 转换为字符串并编码为utf-8
                        fields.append(str(data).encode('utf-8'))
                    writer.writerow(fields)
            QtGui.QMessageBox.information(self, "保存成功", "CSV文件已成功写入!")
        except Exception as e:
            QtGui.QMessageBox.warning(self, "保存失败", f"无法写入文件:{str(e)}")

    @QtCore.pyqtSlot()
    def on_pushButtonWrite_clicked(self):
        self.writeCsv(self.fileName)

    @QtCore.pyqtSlot()
    def on_pushButtonLoad_clicked(self):
        self.loadCsv(self.fileName)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')
    # 注意:Windows路径可以用正斜杠或者双反斜杠
    main = MyWindow("C:/PythonPrograms/sample.csv")
    main.show()
    sys.exit(app.exec_())

关键修复点说明

  • 槽函数移至类内部:把on_pushButtonWrite_clicked和on_pushButtonLoad_clicked作为MyWindow类的成员方法,这样信号(按钮点击)才能正确绑定到槽函数,点击按钮后才会执行对应的逻辑。
  • 编码兼容处理:在Python2中,csv模块处理中文时需要注意编码转换,读取时把字节串解码为Unicode,写入时把字符串编码为utf-8,避免乱码问题。
  • 添加错误处理:用try-except块捕获文件操作中的异常(比如文件不存在、权限不足),并通过Qt的消息框提示用户,方便你快速定位问题。
  • 路径合法性检查:确保你指定的sample.csv路径存在,或者程序有读写该路径的权限,如果路径不对,错误提示会帮你发现这个问题。

内容的提问来源于stack exchange,提问作者Christel Junco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:51:20