简体   繁体   English

在 QTableWidget 中使用 ComboBoxes 时数据不会保存

[英]Data will not save when using ComboBoxes inside QTableWidget

import sys
from PyQt6 import QtWidgets
from PyQt6.QtWidgets import QApplication, QItemDelegate, QWidget, QTableWidget, QTableWidgetItem, QPushButton, QHeaderView, QHBoxLayout, QVBoxLayout
from PyQt6.QtCore import Qt
import pandas as pd


class ComboBoxDelegate(QItemDelegate):
    def __init__(self, parent=None):
        super(ComboBoxDelegate, self).__init__(parent)
        self.items = []

    def setItems(self, items):
        self.items = items

    def createEditor(self, widget, option, index):
        editor = QtWidgets.QComboBox(widget)
        editor.addItems(self.items)
        return editor

    def setEditorData(self, editor, index):
        value = index.model().data(index, Qt.ItemDataRole.EditRole)
        if value:
            editor.setCurrentText(str(value))
            print("Data Changed")

    def setModelData(self, editor, model, index):
        model.setData(index, editor.currentIndex(), Qt.ItemDataRole.EditRole)

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.window_width, self.window_height = 700, 500
        self.resize(self.window_width, self.window_height)
        self.setWindowTitle('Load Excel (or CSV) data to QTableWidget')

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.table = QTableWidget()
        layout.addWidget(self.table)

        self.button = QPushButton('&Load Data')
        self.button.clicked.connect(lambda _, xl_path=excel_file_path,: self.loadExcelData(xl_path))
        layout.addWidget(self.button)

    def loadExcelData(self, excel_file_dir):
        df = pd.read_csv(excel_file_dir)
        if df.size == 0:
            return

        df.fillna('', inplace=True)
        self.table.setRowCount(df.shape[0])
        self.table.setColumnCount(df.shape[1])
        self.table.setHorizontalHeaderLabels(df.columns)

        # returns pandas array object
        for row in df.iterrows():
            values = row[1]
            for col_index, value in enumerate(values):
                if isinstance(value, (float, int)):
                    value = '{0:0,.0f}'.format(value)
                tableItem = QTableWidgetItem(str(value))
                self.table.setItem(row[0], col_index, tableItem)
        self.create_delegate(self.table)
        self.table.setColumnWidth(2, 300)
    
    def create_delegate(self, table):
        test_del = ComboBoxDelegate()
        test_list = ["Gravity Main", "Manhole", "Lateral"]
        test_del.setItems(test_list)
        table.setItemDelegateForColumn(0, test_del)


if __name__ == '__main__':
    
    excel_file_path = "[Your CSV]"

    app = QApplication(sys.argv)
    app.setStyleSheet('''
        QWidget {
            font-size: 17px;
        }
    ''')
    
    myApp = MyApp()
    myApp.show()

    try:
        sys.exit(app.exec())
    except SystemExit:
        print('Closing Window...')

Extension to previous question延伸到上一个问题
Change the file directory to a random csv.将文件目录更改为随机 csv。
This populates the QTableWidget and does the same thing as my main program.这会填充 QTableWidget 并与我的主程序执行相同的操作。
The QTableWidget does not save the changes. QTableWidget 不保存更改。
My goal is to be able to populate multiple columns with different options based on the csv that is loaded.我的目标是能够根据加载的 csv 使用不同的选项填充多个列。 I had a working version but using QTableView instead of QTableWidget and I am working on transferring that progress.我有一个工作版本,但使用 QTableView 而不是 QTableWidget,我正在努力转移该进度。

The issue is caused by a code generation bug , according to the PyQt maintainer. 根据PyQt 维护者的说法,该问题是由代码生成错误引起的。

It should have been fixed in the following PyQt6 snapshots, so it's very likely that if you do a pip update you'll get the working version already, otherwise wait a couple of days and keep an eye on the changelog of the official site .它应该已在以下 PyQt6 快照中修复,因此如果您进行 pip 更新,您很可能已经获得工作版本,否则请等待几天并密切关注官方网站的更新日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM