如何从 QtableWidgetItem 创建字典?
Posted
技术标签:
【中文标题】如何从 QtableWidgetItem 创建字典?【英文标题】:How to create a dictionary from QtableWidgetItem? 【发布时间】:2019-03-23 17:24:37 【问题描述】:我正在将我的数据从 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
【问题讨论】:
【参考方案1】:试试看:
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_())
【讨论】:
谢谢兄弟,但我没有提到我需要这个格式的字典: result = '1111':['Capital 1','145321','94565','', '','','74651','','','24651','','',''], '1112':['大写2','65115','','6149' ,'6645','555641','','','','41245','98416','',''],'1113':['大写3','544453','', '45345453','','555641','434556','','453453','','98416','','453453'],......,键如果您还记得前面的问题,那么它是一个 int 并且值是一个列表 @AnassBelmaati 附上您的tableWidget
与数据的样子
我附上了它,兄弟检查一下
当我添加这条指令时: self.result[v[0]] = (v[1:]) 它为每一行创建一个 Dict 并且每次它附加一个项目时,用它来计算说出我在说什么,谢谢。以上是关于如何从 QtableWidgetItem 创建字典?的主要内容,如果未能解决你的问题,请参考以下文章
void QTableWidget::setItemPrototype ( const QTableWidgetItem * item ) 如何克隆对象?
QTableWidgetItem.itemAt(pos) 在 contextMenu 请求时总是返回 0