在 QtableWidget 中使用字典处理

Handle with dictionary in QtableWidget

我在我的项目中有一个从 CSV 文件导入数据的 CSV 模块。 "generateCsvData"方法将其转换为字典,我想将数据插入到许多QtableWidgets中(取决于一些处理和计算)。例如 "updateData" 可以将一个项目插入到第二个 QtableWidget 的单元格 (24,5) 中,这里的问题是,当我想执行程序和读取设置时,在调试控制台中显示: {} None。 我知道 python 引用全局范围结果的第一个值 = {}

class MyWindow(QMainWindow):
    def __init__(self, aPath, parent=None):
        super(MyWindow, self).__init__(parent)
        self.delimit = '\t'
        self.fileName = ""
        self.result = {}

def generateCsvData(self, fileName):
        f = open(fileName, 'r')
        mystring = f.read()
        if mystring.count(",") > mystring.count('\t'):
            if mystring.count(",") > mystring.count(';'):
                self.delimit = ","
            elif mystring.count(";") > mystring.count(','):
                self.delimit = ";"
            else:
                self.delimit = "\t"
        elif mystring.count(";") > mystring.count('\t'):
            self.delimit = ';'
        else:
            self.delimit = "\t"
        f.close()
        f = open(fileName, 'r') 
        with f:
            f = open(fileName, 'r')
            reader = csv.reader(f, delimiter=self.delimit)
            header=[[head] for head in next(reader)]
            for row in reader:
                key = row[0]  #####
                print(row)
                if key in self.result:
                        pass
                self.result[key] = (row [1:])
            print (self.result)

def updateData(self, k, v, n, m):
    print (self.result)
    #print("Value : %s" % self.result.get(k, "Never"))
    item = self.result.get(k)[v]
    print(item)
    newItem = QTableWidgetItem(str(item))
    newItem.setForeground(QBrush(QColor(255, 0, 0)))
    self.ui.tableWidget_Bilan.setItem(n, m, newItem)

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    app.setApplicationName('MyWindow')
    main = MyWindow('')
    main.updateData(k="11110000", v=0, n=24, m=4)  
    main.setMinimumSize(820, 300)
    main.show()

sys.exit(app.exec_())

当我点击按钮执行 "updateData" 方法时,我得到 TypeError: updateData() missing 3 required positional arguments: 'v', 'n', and 'm'.那么在字典满后我如何使用"updateData"或任何其他方法呢?请有任何想法,谢谢!

试一试:

main.py

import csv
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *

class MyWindow(QMainWindow):
    def __init__(self, aPath, parent=None):
        super(MyWindow, self).__init__(parent)

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setRowCount(55)
        self.tableWidget.setColumnCount(14)

        conLayout = QHBoxLayout(centralWidget)
        conLayout.addWidget(self.tableWidget)

        self.fileName = "csv.csv"                              # +
        self.result   = {}

        self.generateCsvData(self.fileName)                    # +

    def generateCsvData(self, fileName):                       # +
        with open(fileName, "r") as fileInput:                    
            for i, row in enumerate(csv.reader(fileInput)):
                if i:
                    self.result[row[0]] = (row[1:])

    def updateData(self, k, v, n, m):
        [print(kk, vv) for kk, vv in self.result.items()]

        item = self.result.get(k)[v]
        print("\nitem =`{}`".format(item))

        newItem = QTableWidgetItem(str(item))
        newItem.setForeground(QBrush(QColor(255, 0, 0)))
#        self.ui.tableWidget_Bilan.setItem(n, m, newItem)    # -
        self.tableWidget.setItem(n, m, newItem)              # +

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    app.setApplicationName('MyWindow')
    main = MyWindow('')
    main.updateData(k="11110000", v=0, n=24, m=4)  
    main.setMinimumSize(820, 300)
    main.show()
    sys.exit(app.exec_())

csv.csv

key,    item1,  item2, item3,  item4,  item5,  item6,  item7, item8, item9, item10, item11, item12, item13
1111, Title 1,  12521, 94565,       ,       ,       , 684651,      ,      ,  44651,       ,       ,  
1112, Title 2,  65115,      , 466149,  46645, 555641,       ,      ,      , 412045,  98416,       ,  
1113, Title 3, 243968,      ,       , 466149,  46645, 555641, 98656,      ,       , 412045,  98416, 
11110000,Title 4,243968,    ,       , 466149,  46645, 555641, 98656,      ,       , 412045,  98416, 


更新

import csv
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *

class MyWindow(QMainWindow):
    def __init__(self, aPath, parent=None):
        super(MyWindow, self).__init__(parent)

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.tableWidget = QTableWidget(self)
        self.tableWidget.setRowCount(55)
        self.tableWidget.setColumnCount(14)

        button = QPushButton("Select csv file")               # +
        button.clicked.connect(self.selectCsvFile)            # +

        conLayout = QHBoxLayout(centralWidget)
        conLayout.addWidget(self.tableWidget)
        conLayout.addWidget(button)                           # +

        self.fileName = ""                                    # - "csv.csv"                           
        self.result   = {}

    def generateCsvData(self, fileName):                       
        with open(fileName, "r") as fileInput:                    
            for i, row in enumerate(csv.reader(fileInput)):
                if i:
                    self.result[row[0]] = (row[1:])

        if self.result:                                       # +
            self.updateData(k="11110000", v=0, n=24, m=4)     # +   !!!         

    def updateData(self, k, v, n, m):
        if not self.result: return                            # +

        [print(kk, vv) for kk, vv in self.result.items()]

        item = self.result.get(k)[v]
        print("\nitem =`{}`".format(item))

        newItem = QTableWidgetItem(str(item))
        newItem.setForeground(QBrush(QColor(255, 0, 0)))
        self.tableWidget.setItem(n, m, newItem)              

# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv        
    def selectCsvFile(self):
        self.fileName, _ = QFileDialog.getOpenFileName(
                           self, 
                           'Open file', 
                           '',
                           "Csv Files (*.csv)")
        if self.fileName: 
            print("\n {} \n".format(self.fileName))
            self.generateCsvData(self.fileName)
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    


if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    app.setApplicationName('MyWindow')
    main = MyWindow('')
#    main.updateData(k="11110000", v=0, n=24, m=4)            # --- !!!
    main.setMinimumSize(820, 300)
    main.show()
    sys.exit(app.exec_())