如何从 QtableWidgetItem 创建字典?

How to create a dictionary from QtableWidgetItem?

我正在将 CSV 文件中的数据检索到 QtableWidget 中,我创建了一些方法来修改、删除、插入列和行,甚至是新项目...在 QtableWidget 中,所以在进入下一步之前我需要将当前的 QtableWidgetItem 转换为字典。(不是文件中的数据!)通过按下按钮。

class MyWindow(QMainWindow):
def __init__(self, *args, parent=None):
    super(MyWindow, self).__init__(parent)
        self.fileName = ""
        self.result = {}

##### Event for the button
      self.ui.commandLinkButton.clicked.connect(self.generateCsvData)

 def loadCsvOnOpen(self, fileName): #Load CSV file
 if 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') 
        self.ui.tableView.setRowCount(0)
        self.ui.tableView.setColumnCount(0)
        for rowdata in csv.reader(f, delimiter=self.delimit):
            row = self.ui.tableView.rowCount()
            self.ui.tableView.insertRow(row)
            if len(rowdata) == 0:
                self.ui.tableView.setColumnCount(len(rowdata) + 1)
            else:
                self.ui.tableView.setColumnCount(len(rowdata))
            for column, data in enumerate(rowdata):
                item = QTableWidgetItem(data)
                self.ui.tableView.setItem(row, column, item)   
    self.ui.tableView.selectRow(0)
    self.isChanged = False
    self.setCurrentFile(fileName)
    self.ui.tableView.resizeColumnsToContents()
    self.ui.tableView.resizeRowsToContents()
    self.msg(fileName + " loaded")

 def generateCsvData(self): 
    for row in range(self.ui.tableView.rowCount()):
        for column in range(self.ui.tableView.columnCount()):
            item = self.ui.tableView.item(row, column)
            if item is not None:
                self.result[row[0]] = (row[1:])
                print(self.result)
            else:
                return

试一试:

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

class Example(QDialog):
    def __init__(self):
        super().__init__()

        self.tableWidget = QTableWidget()

        self.result = {}
        button = QPushButton("Create a dictionary from QtableWidgetItem")
        button.clicked.connect(self.generateCsvData)                     # <---

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.tableWidget) 
        self.layout.addWidget(button)
        self.setLayout(self.layout) 

        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(2)

        for i in range(4):
            for j in range(2):
                item = QTableWidgetItem("Item {}-{}".format(i, j))
                item.setTextAlignment(Qt.AlignHCenter)
                self.tableWidget.setItem(i, j, item)

    def generateCsvData(self):                                           # <---
        for row in range(self.tableWidget.rowCount()):
            for column in range(self.tableWidget.columnCount()):   
                item = self.tableWidget.item(row, column).text()   

                k = "{:0>3}:{:0>3}".format(row, column)
                v = "{}".format(item)
                self.result[k] = v

        print("\n  key    value")
        [ print(k, v) for k, v in self.result.items()]


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Example()
    w.show()
    sys.exit(app.exec_())


更新

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

class Example(QDialog):
    def __init__(self):
        super().__init__()

        self.tableWidget = QTableWidget()

        self.result = {}
        button = QPushButton("Create a dictionary from QtableWidgetItem")
        button.clicked.connect(self.generateCsvData)                     # <---

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.tableWidget) 
        self.layout.addWidget(button)
        self.setLayout(self.layout) 

        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(5)

        for i in range(4):
            for j in range(5):
                if j == 0: 
                    item = QTableWidgetItem("111{}".format(i))
                else:
                    item = QTableWidgetItem("Item {}-{}".format(i, j))

                item.setTextAlignment(Qt.AlignHCenter)
                self.tableWidget.setItem(i, j, item)

    def generateCsvData(self):                                           # <---
        for row in range(self.tableWidget.rowCount()):
            v = []
            for column in range(self.tableWidget.columnCount()):   
                if column == 0:
                    k = self.tableWidget.item(row, column).text()
                else:
                    item = self.tableWidget.item(row, column).text() 
                    v.append(item)                    

                self.result[k] = v

        print("\n key    value")
        [ print(k, v) for k, v in self.result.items()]


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Example()
    w.show()
    sys.exit(app.exec_())