Python CRUD实例函数使pyqt5 GUI崩溃

问题描述 投票:0回答:1

我创建了一个简单的CRUD程序,需要将其转换为GUI。我的crud函数以前没有问题,但是在删除qtableview中的相同项目后调用它们时,软件崩溃了。我可以成功创建一个新的记录对象,将其添加到tablewidget,内存数组中,还可以更新数据库。我可以使用QTableWidget.currentRow()中的索引从qtableview中删除,但是我不能使用删除函数使用相同的索引从数据库中删除记录,我可以使用QTableWidget.currentRow()和QTableWidget.currentColumn( ),但不能使用相同的值从内存列表或数据库中删除数据。

我的列表加载数据,但是当尝试执行任何我的原始方法时,应用程序停止。

LayoutManager.py

import pandas as pd
import numpy as np
import sqlite3
import csv
import CheeseRecord


class ListManager:
    """ ListManagement class to perform function on the list of records """
    cheese_list = []
    target_database = 'database.sqlite'
    cheese_frame = pd.DataFrame

    def __init__(self, csv_location, database_location):

        self.csv_location = csv_location
        self.database_location = database_location
        self.conn = sqlite3.connect(database_location)

    """ constructor """

    def csv_to_dataframe(self):
        """ Function to parse csv file for desired columns, stores them in a Pandas Dataframe """
        try:
            self.cheese_frame = pd.read_csv(self.csv_location,
                                            usecols=['CheeseId', 'CheeseNameEn', 'ManufacturerNameEn', 'ManufacturerProvCode',
 'ManufacturingTypeEn', 'WebSiteEn', 'FatContentPercent',
                                                     'MoisturePercent',
                                                     'ParticularitiesEn', 'FlavourEn', 'CharacteristicsEn',
                                                     'RipeningEn',
                                                     'Organic',
                                                     'CategoryTypeEn', 'MilkTypeEn', 'MilkTreatmentTypeEn',
                                                     'RindTypeEn',
                                                     'LastUpdateDate'])
        except IOError as e:
            print(e)

        print("CSV Loaded to Memory and Stored in a Pandas Dataframe")

    def dataframe_to_list(self):
        """ Function to create a list of cheeseRecord objects """

        """ replace pandas null field (nan) with whitespace"""
        self.cheese_frame.replace(np.nan, '', regex=True)
        """iterate over reach row and create CheeseRecord object using the csv fields """
        for index, rows in self.cheese_frame.iterrows():
            temp_record = CheeseRecord.CheeseRecord(rows[0], rows[1], rows[2], rows[3], rows[4], rows[5], rows[6],
                                                    rows[7],
                                                    rows[8],
                                                    rows[9], rows[10], rows[11], rows[12], rows[13], rows[14], rows[15],
                                                    rows[16],
                                                    rows[17])
            self.cheese_list.append(temp_record)
            """add newly created record to the list"""
        print("Pandas DataFrame converted to List of CheeseRecord Objects")

    def dataframe_to_database_table(self):
        """function to dump the pandas dataframe into a table in my database, if the table already exists overwrite it"""
        self.cheese_frame.to_sql(name='cheeseData', con=self.conn, if_exists='replace', index=False)
        print("Database Created")

    def add_record(self, cheese_record):
        """function to add a record"""
        """first add to list in memory"""
        self.cheese_list.append(cheese_record)
        print("record added to end of list")
        """then add to database table"""
        self.add_database_record(cheese_record)

    def return_list_object(self):
        return self

    def new_record(self, Cheese_id, CheeseNameEn, ManufacturerNameEn,
                   ManufacturerProvCode, ManufacturingTypeEn, WebSiteEn,
                   FatContentPercent, MoisturePercent, ParticularitiesEn, FlavourEn,
                   CharacteristicsEn, RipeningEn, Organic, CategoryTypeEn,
                   MilkTypeEn, MilkTreatmentTypeEn, RindTypeEn,
                   LastUpdateDate):
        return CheeseRecord.CheeseRecord(Cheese_id, CheeseNameEn, ManufacturerNameEn,
                                         ManufacturerProvCode, ManufacturingTypeEn, WebSiteEn,
                                         FatContentPercent, MoisturePercent, ParticularitiesEn, FlavourEn,
                                         CharacteristicsEn, RipeningEn, Organic, CategoryTypeEn,
                                         MilkTypeEn, MilkTreatmentTypeEn, RindTypeEn,
                                         LastUpdateDate)

    def print_list(self):

        """function to print out list of cheese records"""

        for index in self.cheese_list:
            print(index.convert_to_string())

    def print_at_index(self, index):

        """function to print cheese record at index"""
        print(self.cheese_list[index].convert_to_string())

    def delete_at_index(self, index):

        """function to delete cheese record at index"""
        """first delete from list in memory"""
        self.cheese_list.pop(index)
        print("item at index " + str(index) + " deleted")
        """then delete from database"""
        self.delete_database_record(index)

    def write_to_csv(self):

        """function to write list from memory to data.csv"""
        with open('data.csv', 'w', ) as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(['cheese_id', 'CheeseNameEn', 'ManufacturerNameEn',
                             'ManufacturerProvCode', 'ManufacturingTypeEn', 'WebSiteEn',
                             'FatContentPercent', 'MoisturePercent', 'ParticularitiesEn', 'FlavourEn',
                             'CharacteristicsEn', 'RipeningEn', 'Organic', 'CategoryTypeEn',
                             'MilkTypeEn', 'MilkTreatmentTypeEn', 'RindTypeEn',

                             'LastUpdateDate'])
            for index in self.cheese_list:
                writer.writerow(
                    [str(index.CheeseId), index.CheeseNameEn, index.ManufacturerNameEn, index.ManufacturerProvCode,
                     index.ManufacturingTypeEn, index.WebSiteEn, index.FatContentPercent, index.MoisturePercent,
                     index.ParticularitiesEn, index.FlavourEn, index.CharacteristicsEn, index.RipeningEn, index.Organic,
                     index.CategoryTypeEn, index.MilkTypeEn, index.MilkTreatmentTypeEn, index.RindTypeEn,
                     index.LastUpdateDate])
        print("Dataset written to data.csv\n")

    def edit_at_index(self, index: int, row: int, value: str):
        """function to edit cheese record instance field at index, row"""

        if row == 0:
            self.cheese_list[index].CheeseId = value
        elif row == 1:
            self.cheese_list[index].CheeseNameEn = value
        elif row == 2:
            self.cheese_list[index].ManufacturerNameEn = value
        elif row == 3:
            self.cheese_list[index].ManufacturerProvCode = value
        elif row == 4:
            self.cheese_list[index].ManufacturingTypeEn = value
        elif row == 5:
            self.cheese_list[index].WebSiteEn = value
        elif row == 6:
            self.cheese_list[index].FatContentPercent = value
        elif row == 7:
            self.cheese_list[index].MoisturePercent = value
        elif row == 8:
            self.cheese_list[index].ParticularitiesEn = value
        elif row == 9:
            self.cheese_list[index].FlavourEn = value
        elif row == 10:
            self.cheese_list[index].CharacteristicsEn = value
        elif row == 11:
            self.cheese_list[index].RipeningEn = value
        elif row == 12:
            self.cheese_list[index].Organic = value
        elif row == 13:
            self.cheese_list[index].CategoryTypeEn = value
        elif row == 14:
            self.cheese_list[index].MilkTypeEn = value
        elif row == 15:
            self.cheese_list[index].MilkTreatmentTypeEn = value
        elif row == 16:
            self.cheese_list[index].RindTypeEn = value
        elif row == 17:
            self.cheese_list[index].LastUpdateDate = value
        print("Value Updated\n")
        print(self.cheese_list[index].convert_to_string())

    def add_database_record(self, cheese_record):
        """function to add a new record to the database"""
        cursor = self.conn.cursor()
        sql_insert_query = '''INSERT INTO cheeseData(CheeseId, CheeseNameEn, ManufacturerNameEn,
                 ManufacturerProvCode, ManufacturingTypeEn, WebSiteEn,
                 FatContentPercent, MoisturePercent, ParticularitiesEn, FlavourEn,
                 CharacteristicsEn, RipeningEn, Organic, CategoryTypeEn,
                 MilkTypeEn, MilkTreatmentTypeEn, RindTypeEn,
                 LastUpdateDate)VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''
        row_data = (cheese_record.CheeseId, cheese_record.CheeseNameEn, cheese_record.ManufacturerNameEn,
                    cheese_record.ManufacturerProvCode, cheese_record.ManufacturingTypeEn, cheese_record.WebSiteEn,
                    cheese_record.FatContentPercent, cheese_record.MoisturePercent, cheese_record.ParticularitiesEn,
                    cheese_record.FlavourEn, cheese_record.CharacteristicsEn, cheese_record.RipeningEn,
                    cheese_record.Organic, cheese_record.CategoryTypeEn, cheese_record.MilkTypeEn,
                    cheese_record.MilkTreatmentTypeEn, cheese_record.RindTypeEn, cheese_record.LastUpdateDate)
        cursor.execute(sql_insert_query, row_data)
        self.conn.commit()
        cursor.close()

    def delete_database_record(self, index):
        """function to delete a database record at index"""
        delete_cursor = self.conn.cursor()
        delete_cursor.execute('''DELETE from cheeseData where rowid=?''', (index,))
        print("Record deleted at rowid = " + str(index))
        delete_cursor.close()

    def commit_and_close(self):
        self.conn.commit()
        self.conn.close()
        print("Connection Closed")

Main.py

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QInputDialog, QLineEdit

import ListManager


class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.cheese_list = ListManager.ListManager('canadianCheeseDirectory.csv', 'canadianCheeseDirectory.sqlite')
        self.input_CheeseId = QLineEdit(MainWindow)
        self.input_CheeseNameEn = QLineEdit(MainWindow)
        self.input_ManufacturerNameEn = QLineEdit(MainWindow)
        self.input_ManufacturerProvCode = QLineEdit(MainWindow)
        self.input_ManufacturingTypeEn = QLineEdit(MainWindow)
        self.input_WebSiteEn = QLineEdit(MainWindow)
        self.input_FatContentPercent = QLineEdit(MainWindow)
        self.input_MoisturePercent = QLineEdit(MainWindow)
        self.input_ParticularitiesEn = QLineEdit(MainWindow)
        self.input_FlavourEn = QLineEdit(MainWindow)
        self.input_CharacteristicsEn = QLineEdit(MainWindow)
        self.input_RipeningEn = QLineEdit(MainWindow)
        self.input_Organic = QLineEdit(MainWindow)
        self.input_CategoryTypeEn = QLineEdit(MainWindow)
        self.input_MilkTypeEn = QLineEdit(MainWindow)
        self.input_MilkTreatmentTypeEn = QLineEdit(MainWindow)
        self.input_RindTypeEn = QLineEdit(MainWindow)
        self.input_LastUpdateDate = QLineEdit(MainWindow)
        self.input_editInput = QLineEdit(MainWindow)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.delete_button = QtWidgets.QPushButton(self.centralwidget)
        self.delete_button.setGeometry(QtCore.QRect(710, 180, 75, 23))
        self.delete_button.setObjectName("delete_button")
        self.delete_button.clicked.connect(self.deleteRecord)

        self.create_button = QtWidgets.QPushButton(self.centralwidget)
        self.create_button.setGeometry(QtCore.QRect(710, 120, 75, 23))
        self.create_button.setObjectName("create_button")
        self.create_button.clicked.connect(self.showDialogAdd)

        self.edit_button = QtWidgets.QPushButton(self.centralwidget)
        self.edit_button.setGeometry(QtCore.QRect(710, 150, 75, 23))
        self.edit_button.setObjectName("edit_button")
        self.edit_button.clicked.connect(self.showDialogEdit)
        self.close_button = QtWidgets.QPushButton(self.centralwidget)
        self.close_button.setGeometry(QtCore.QRect(710, 550, 75, 23))
        self.close_button.setObjectName("close_button")
        self.load_button = QtWidgets.QPushButton(self.centralwidget)
        self.load_button.setGeometry(QtCore.QRect(710, 10, 75, 23))
        self.load_button.setObjectName("load_button")
        self.load_button.clicked.connect(self.loadData)
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(0, 0, 701, 591))
        self.tableWidget.setColumnCount(19)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setRowCount(0)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setText("")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.delete_button.setText(_translate("MainWindow", "Delete"))
        self.create_button.setText(_translate("MainWindow", "Create"))
        self.edit_button.setText(_translate("MainWindow", "Edit"))
        self.close_button.setText(_translate("MainWindow", "Close"))
        self.load_button.setText(_translate("MainWindow", "Load"))

    def loadData(self):

        self.cheese_list.csv_to_dataframe()
        self.cheese_list.dataframe_to_database_table()

        results = self.cheese_list.conn.execute("SELECT * FROM cheeseData")

        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(row_number, column_number, QtWidgets.QTableWidgetItem(str(data)))

    def deleteRecord(self):

        row = self.tableWidget.currentRow()
        column = self.tableWidget.currentColumn()
        self.tableWidget.removeRow(row)




    def createRecord(self):
        self.tableWidget.setRowCount(self.tableWidget.rowCount() + 1)
        tempObject = self.cheese_list.new_record(self.input_CheeseId, self.input_CheeseNameEn,
                                                 self.input_ManufacturerNameEn,
                                                 self.input_ManufacturerProvCode, self.input_ManufacturingTypeEn,
                                                 self.input_WebSiteEn, self.input_FatContentPercent,
                                                 self.input_MoisturePercent, self.input_ParticularitiesEn,
                                                 self.input_FlavourEn, self.input_CharacteristicsEn,
                                                 self.input_RipeningEn, self.input_Organic, self.input_CategoryTypeEn,
                                                 self.input_MilkTypeEn, self.input_MilkTreatmentTypeEn,
                                                 self.input_RindTypeEn, self.input_LastUpdateDate)

        self.cheese_list.add_record(tempObject)

        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 0,
                                 QtWidgets.QTableWidgetItem(str(self.input_CheeseId)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 1,
                                 QtWidgets.QTableWidgetItem(str(self.input_CheeseNameEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 2,
                                 QtWidgets.QTableWidgetItem(str(self.input_ManufacturerNameEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 3,
                                 QtWidgets.QTableWidgetItem(str(self.input_ManufacturerProvCode)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 4,
                                 QtWidgets.QTableWidgetItem(str(self.input_ManufacturingTypeEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 5,
                                 QtWidgets.QTableWidgetItem(str(self.input_WebSiteEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 6,
                                 QtWidgets.QTableWidgetItem(str(self.input_FatContentPercent)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 7,
                                 QtWidgets.QTableWidgetItem(str(self.input_MoisturePercent)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 8,
                                 QtWidgets.QTableWidgetItem(str(self.input_ParticularitiesEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 9,
                                 QtWidgets.QTableWidgetItem(str(self.input_FlavourEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 10,
                                 QtWidgets.QTableWidgetItem(str(self.input_CharacteristicsEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 11,
                                 QtWidgets.QTableWidgetItem(str(self.input_RipeningEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 12,
                                 QtWidgets.QTableWidgetItem(str(self.input_Organic)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 13,
                                 QtWidgets.QTableWidgetItem(str(self.input_CategoryTypeEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 14,
                                 QtWidgets.QTableWidgetItem(str(self.input_MilkTypeEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 15,
                                 QtWidgets.QTableWidgetItem(str(self.input_MilkTreatmentTypeEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 16,
                                 QtWidgets.QTableWidgetItem(str(self.input_RindTypeEn)))
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 17,
                                 QtWidgets.QTableWidgetItem(str(self.input_LastUpdateDate)))

    def editRecord(self):

        row = self.tableWidget.currentRow()
        column = self.tableWidget.currentColumn()
        self.tableWidget.setItem(row, column,
                                 QtWidgets.QTableWidgetItem(str(self.input_editInput)))


    def showDialogAdd(self):

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog',
                                               'Enter your name:', QLineEdit.Normal)
        if okPressed:
            self.input_CheeseId = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_CheeseNameEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_ManufacturerNameEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_ManufacturerProvCode = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_ManufacturingTypeEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_WebSiteEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_FatContentPercent = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_MoisturePercent = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_ParticularitiesEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_FlavourEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_CharacteristicsEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_RipeningEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_Organic = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_CategoryTypeEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_MilkTypeEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_MilkTreatmentTypeEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_RindTypeEn = text

        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog', 'Enter your name', QLineEdit.Normal)
        if okPressed:
            self.input_LastUpdateDate = text

        self.createRecord()

    def showDialogEdit(self):
        text, okPressed = QInputDialog.getText(MainWindow, 'Input Dialog',
                                               'Enter your name:', QLineEdit.Normal)
        if okPressed:
            self.input_editInput = text
            self.editRecord()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

CheeseRecord.py导入csv#Sean Di Rienzo

class CheeseRecord:
    """ CheeseRecord object """

    def __init__(self, cheese_id, CheeseNameEn, ManufacturerNameEn,
                 ManufacturerProvCode, ManufacturingTypeEn, WebSiteEn,
                 FatContentPercent, MoisturePercent, ParticularitiesEn, FlavourEn,
                 CharacteristicsEn, RipeningEn, Organic, CategoryTypeEn,
                 MilkTypeEn, MilkTreatmentTypeEn, RindTypeEn,
                 LastUpdateDate):
        """Constructor , taking in parameters for the desired fields from the csv"""

        self.CheeseId = cheese_id
        self.CheeseNameEn = CheeseNameEn
        self.ManufacturerNameEn = ManufacturerNameEn
        self.ManufacturerProvCode = ManufacturerProvCode
        self.ManufacturingTypeEn = ManufacturingTypeEn
        self.WebSiteEn = WebSiteEn
        self.FatContentPercent = FatContentPercent
        self.MoisturePercent = MoisturePercent
        self.ParticularitiesEn = ParticularitiesEn
        self.FlavourEn = FlavourEn
        self.CharacteristicsEn = CharacteristicsEn
        self.RipeningEn = RipeningEn
        self.Organic = Organic
        self.CategoryTypeEn = CategoryTypeEn
        self.MilkTypeEn = MilkTypeEn
        self.MilkTreatmentTypeEn = MilkTreatmentTypeEn
        self.RindTypeEn = RindTypeEn
        self.LastUpdateDate = LastUpdateDate



    def convert_to_string(self):
        """ Returns a string with the CheeseObject's data """
        cheese_record_string = " "
        cheese_record_string += str(self.CheeseId) + " | "
        cheese_record_string += str(self.CheeseNameEn) + " | "
        cheese_record_string += str(self.ManufacturerNameEn) + " | "
        cheese_record_string += str(self.ManufacturerProvCode) + " | "
        cheese_record_string += str(self.ManufacturingTypeEn) + " | "
        cheese_record_string += str(self.WebSiteEn) + " | "
        cheese_record_string += str(self.FatContentPercent) + " | "
        cheese_record_string += str(self.MoisturePercent) + " | "
        cheese_record_string += str(self.ParticularitiesEn) + " | "
        cheese_record_string += str(self.FlavourEn) + " | "
        cheese_record_string += str(self.CharacteristicsEn) + " | "
        cheese_record_string += str(self.RipeningEn) + " | "
        cheese_record_string += str(self.Organic) + " | "
        cheese_record_string += str(self.CategoryTypeEn) + " | "
        cheese_record_string += str(self.MilkTypeEn) + " | "
        cheese_record_string += str(self.MilkTreatmentTypeEn) + " | "
        cheese_record_string += str(self.RindTypeEn) + " | "
        cheese_record_string += str(self.LastUpdateDate)

        return cheese_record_string
python python-3.x pyqt pyqt5
1个回答
0
投票

您有以下错误:

  • 您使用名称来为其分配为其创建其他值,例如,input_CheeseId是QLineEdit,但随后使用input_CheeseId存储文本,并且在下一次您想使用input_CheeseId获取QLineEdit的文本时,这已经是产生错误的文本。

  • 另一个更简单的错误是PyQt建议不要修改Qt Designer生成的类,而是创建一个从适当的小部件继承的类,并使用初始类填充小部件(有关更多信息,请参见this)。

考虑到上述,解决方法是:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QInputDialog, QLineEdit

import ListManager


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.input_CheeseId = QLineEdit(MainWindow)
        self.input_CheeseNameEn = QLineEdit(MainWindow)
        self.input_ManufacturerNameEn = QLineEdit(MainWindow)
        self.input_ManufacturerProvCode = QLineEdit(MainWindow)
        self.input_ManufacturingTypeEn = QLineEdit(MainWindow)
        self.input_WebSiteEn = QLineEdit(MainWindow)
        self.input_FatContentPercent = QLineEdit(MainWindow)
        self.input_MoisturePercent = QLineEdit(MainWindow)
        self.input_ParticularitiesEn = QLineEdit(MainWindow)
        self.input_FlavourEn = QLineEdit(MainWindow)
        self.input_CharacteristicsEn = QLineEdit(MainWindow)
        self.input_RipeningEn = QLineEdit(MainWindow)
        self.input_Organic = QLineEdit(MainWindow)
        self.input_CategoryTypeEn = QLineEdit(MainWindow)
        self.input_MilkTypeEn = QLineEdit(MainWindow)
        self.input_MilkTreatmentTypeEn = QLineEdit(MainWindow)
        self.input_RindTypeEn = QLineEdit(MainWindow)
        self.input_LastUpdateDate = QLineEdit(MainWindow)
        self.input_editInput = QLineEdit(MainWindow)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.delete_button = QtWidgets.QPushButton(self.centralwidget)
        self.delete_button.setGeometry(QtCore.QRect(710, 180, 75, 23))
        self.delete_button.setObjectName("delete_button")

        self.create_button = QtWidgets.QPushButton(self.centralwidget)
        self.create_button.setGeometry(QtCore.QRect(710, 120, 75, 23))
        self.create_button.setObjectName("create_button")

        self.edit_button = QtWidgets.QPushButton(self.centralwidget)
        self.edit_button.setGeometry(QtCore.QRect(710, 150, 75, 23))
        self.edit_button.setObjectName("edit_button")
        self.close_button = QtWidgets.QPushButton(self.centralwidget)
        self.close_button.setGeometry(QtCore.QRect(710, 550, 75, 23))
        self.close_button.setObjectName("close_button")
        self.load_button = QtWidgets.QPushButton(self.centralwidget)
        self.load_button.setGeometry(QtCore.QRect(710, 10, 75, 23))
        self.load_button.setObjectName("load_button")

        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(0, 0, 701, 591))
        self.tableWidget.setColumnCount(19)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setRowCount(0)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setText("")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.delete_button.setText(_translate("MainWindow", "Delete"))
        self.create_button.setText(_translate("MainWindow", "Create"))
        self.edit_button.setText(_translate("MainWindow", "Edit"))
        self.close_button.setText(_translate("MainWindow", "Close"))
        self.load_button.setText(_translate("MainWindow", "Load"))


class Dialog(QtWidgets.QDialog):
    def __init__(self, names, parent=None):
        super().__init__(parent)

        self.line_edits = []

        scrollarea = QtWidgets.QScrollArea(widgetResizable=True)
        widget = QtWidgets.QWidget()
        scrollarea.setWidget(widget)
        flay = QtWidgets.QFormLayout(widget)

        for name in names:
            le = QtWidgets.QLineEdit()
            flay.addRow(name, le)
            self.line_edits.append(le)

        buttonBox = QtWidgets.QDialogButtonBox()
        buttonBox.setOrientation(QtCore.Qt.Horizontal)
        buttonBox.setStandardButtons(
            QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok
        )

        vlay = QtWidgets.QVBoxLayout(self)
        vlay.addWidget(scrollarea)
        vlay.addWidget(buttonBox)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

    def get_results(self):
        return [le.text() for le in self.line_edits]


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.cheese_list = ListManager.ListManager(
            "canadianCheeseDirectory.csv", "canadianCheeseDirectory.sqlite"
        )
        self.load_button.clicked.connect(self.loadData)
        self.edit_button.clicked.connect(self.showDialogEdit)
        self.delete_button.clicked.connect(self.deleteRecord)
        self.create_button.clicked.connect(self.showDialogAdd)

    @QtCore.pyqtSlot()
    def loadData(self):
        self.cheese_list.csv_to_dataframe()
        self.cheese_list.dataframe_to_database_table()
        results = self.cheese_list.conn.execute("SELECT * FROM cheeseData")
        self.tableWidget.clear()
        self.tableWidget.setHorizontalHeaderLabels(list(self.cheese_list.cheese_frame))
        for row_number, row_data in enumerate(results):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                self.tableWidget.setItem(
                    row_number, column_number, QtWidgets.QTableWidgetItem(str(data))
                )

    @QtCore.pyqtSlot()
    def deleteRecord(self):
        row = self.tableWidget.currentRow()
        column = self.tableWidget.currentColumn()
        self.tableWidget.removeRow(row)

    def createRecord(self, values):
        self.tableWidget.setRowCount(self.tableWidget.rowCount() + 1)
        tempObject = self.cheese_list.new_record(*values)

        self.cheese_list.add_record(tempObject)

        for i, value in enumerate(values):
            self.tableWidget.setItem(
                self.tableWidget.rowCount() - 1, i, QtWidgets.QTableWidgetItem(value)
            )

    def editRecord(self, text):
        row = self.tableWidget.currentRow()
        column = self.tableWidget.currentColumn()
        self.tableWidget.setItem(row, column, QtWidgets.QTableWidgetItem(text))

    @QtCore.pyqtSlot()
    def showDialogAdd(self):
        dialog = Dialog(list(self.cheese_list.cheese_frame), self)
        if dialog.exec_() == QtWidgets.QDialog.Accepted:
            values = dialog.get_results()
            self.createRecord(values)

    @QtCore.pyqtSlot()
    def showDialogEdit(self):
        text, okPressed = QInputDialog.getText(
            self, "Input Dialog", "Enter your name:", QLineEdit.Normal
        )
        if okPressed:
            self.editRecord(text)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.