0
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QDialog
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QLabel
import re



import sys

class Window(QDialog):
    def __init__(self):
        super(Window,self).__init__()
        uic.loadUi("formDialog.ui",self)
        self.button = self.findChild(QPushButton,"submit")
        self.cancelButton = self.findChild(QPushButton,"cancelButton")


        self.text = self.findChild(QLineEdit, "locationLineEdit")
        self.date = self.findChild(QLineEdit, "dateLineEdit")
        self.iso = self.findChild(QLineEdit,"isoEdit")
        ##self.date.setText("ggg")
        self.newCases = self.findChild(QLineEdit, "newCasesLineEdit")
        self.newDeaths = self.findChild(QLineEdit, "newDeathsLineEdit")



        self.button.clicked.connect(self.preSubmitValue)
        self.error = self.findChild(QLabel,"errorLabel")
        self.error.setHidden(True)






    def verifyString(self,value):
        if value == "" or   not value.isalpha():
            return True
        return False


    def verifyNumber(self,value):
        if value == "" or not value.isdigit():
            return True
        return False

    def preSubmitValue(self):
        if self.verifyString(self.text.text()) == False and self.verifyNumber(self.newCases.text()) == False and self.verifyNumber(self.newDeaths.text()) == False and self.verifyString(self.iso.text())==False and self.verifyDate(self.date.text()) == False:
            self.submitValue()

        else:
            self.error.setText("<font color='red'>Please fill out the fields properly</font>")
            self.error.setHidden(False)
            return False





    def submitValue(self):
        location,cases,deaths,iso,date= self.text.text(),self.newCases.text(),self.newDeaths.text(),self.iso.text(),self.date.text()
        return location,cases,deaths,iso,date

    def verifyDate(self,value):
        text = r"\d{4}[-/]\d{2}[-/]\d{2}"
        if  self.date.text() !="" and re.match(text,self.date.text()):
            return False
        return True

THis is the QDIALOG ABOVE

import sys
import csv
from main import Window
from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QAction
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QMenu
from PyQt5.QtSql import QSqlTableModel
from PyQt5.QtSql import QSqlQuery
from PyQt5.QtWidgets import QTableView
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import QStatusBar
from PyQt5.QtWidgets import QLineEdit


class Menu(QMainWindow):
    model = None
    con = None
    cursor = None
    length = 102
    addButton = None
    deleteBtton = None

    def __init__(self):
        super(Menu, self).__init__()
        self.resize(415, 200)
        self.setWindowTitle("CODY HOWARD COVID CASES")
        self.createWidgets()
        toolbar = self.addToolBar("&MEnu")
        toolbar.addWidget(self.addButton)
        toolbar.addWidget(self.deleteBtton)
        toolbar.addWidget(self.searchField)
        self.createStatusBar()
        self.createConnection()
        self.model = QSqlTableModel(self)
        self.model.setTable("CovidCases")
        self.model.setEditStrategy(QSqlTableModel.OnFieldChange)
        self.model.setHeaderData(0, Qt.Horizontal, "ISO_CODE")
        self.model.setHeaderData(1, Qt.Horizontal, "Location")
        self.model.setHeaderData(2, Qt.Horizontal, "Date")
        self.model.setHeaderData(3, Qt.Horizontal, "New_cases")
        self.model.setHeaderData(4, Qt.Horizontal, "New_deaths")
        self.loadData()
        self.addButton.clicked.connect(self.addNewRow)
        # Set up the view
        self.view = QTableView()
        self.view.setModel(self.model)
        self.view.setWindowTitle("VIEW")
        self.view.resizeRowsToContents()
        for i in range(5):
            self.view.setColumnWidth(i, 400)
        self.setCentralWidget(self.view)

    def createStatusBar(self):
        status = QStatusBar()
        status.showMessage("To update any of the cases, double click on a cell and Press enter after edit")
        self.setStatusBar(status)

    def createWidgets(self):
        self.addButton = QPushButton("Add new Row")
        self.deleteBtton = QPushButton("Delete a row")
        self.searchField = QLineEdit("Search")

    def addNewRow(self):##Here this is the method where i start the window, the program is meant to take some data from the QDIALOG and insert it into the QSQLTABLEMODEL BUT ALWAYS CRASHES AFTER IT EXITS
        win = Window()
        win.exec()_
        location, cases, deaths, iso, date = win.submitValue()
        print("fff0" + str(value1) + str(cases) + str(deaths) + iso + date)
        row = self.model.record()
        row.setValue("ISO_CODE", iso)
        row.setValue("Location", location)
        row.setValue("Date", date)
        row.setValue("New_Cases", cases)
        row.setValue("New_deaths", deaths)
        self.model.insertRecord(-1, row)


    def loadData(self):
        print("d")
        file = "C:\\Users\\Gabri\\Downloads\\owid-covid-data.csv"
        with open(file, mode="r") as csvFile:
            csvReader = csv.reader(csvFile);
            headers = next(csvReader);
            row = self.model.record()
            print("Programmed by Cody H")
            x = 0;
            while x <= 100:
                for lines in csvReader:
                    self.insert = (lines[0], lines[1], lines[2], lines[3], lines[4]);
                    row.setValue("ISO_CODE", lines[0])
                    row.setValue("Location", lines[1])
                    row.setValue("Date", lines[2])
                    row.setValue("New_Cases", lines[3])
                    row.setValue("New_deaths", lines[4])
                    self.model.insertRecord(x, row)
                    x += 1;
                    if x >= self.length:
                        break;

    def createConnection(self):
        self.con = QSqlDatabase.addDatabase("QSQLITE")
        self.con.setDatabaseName(r"C:\Users\Gabri\PycharmProjects\PyQT\recordsTest.sqlite")
        if not self.con.open():
            QMessageBox.critical(
                None,
                "QTableView Example - Error!",
                "Database Error: %s" % con.lastError().databaseText(),
            )
            sys.exit(1)
        self.cursor = QSqlQuery()
        self.cursor.exec(
            """
            CREATE TABLE CovidCases (
                 iso_code integer NOT NULL, 
    location text NOT NULL, 
    date text NOT NULL, 
    new_cases integer NOT NULL, 
    new_deaths varchar(255)  

            )
            """
        )
        print(self.con.tables())


app = QApplication(sys.argv)
win = Menu()
win.show()

sys.exit(app.exec_())

The Qdialog is a form that takes data to pass to the other window in the "AddNewRow" method of the QmainWindow so I can insert it into the database. The Qdialog opens fine and takes the data but once I clicked submit (the program is meant to return the values from the form and close the Qdialog but once it closes the program hangs then crashes. what I may be doing wrong? Is there a specific way to exit the QDialog?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Gabriel
  • 53
  • 5
  • Unfortunately, your example is not a [minimal, reproducible one](https://stackoverflow.com/help/minimal-reproducible-example), so it's a bit hard to understand what's going on here. Also there's a typo in `addNewRow`, as there's an underscore after `win.exec()`, but I believe it's only a copy/paste issue as it would throw a syntax error to begin with. Have you tried to run it on a terminal/prompt, to see if there's any traceback of the crash (and ensure that it correctly prints what `addNewRow` should. – musicamante Mar 29 '21 at 14:05
  • `value1` in `Menu.addNewRow` is undefined. – Heike Mar 29 '21 at 14:08

0 Answers0