Python Forum
Close and Open QDialog from QDialog 2 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Close and Open QDialog from QDialog 2 (/thread-37703.html)



Close and Open QDialog from QDialog 2 - ITSRL - Jul-11-2022

So, I have two QDialogs in 2 different classes, in one Qdialog I have a QTableWidget with some data from a MYSQL db, I want to close and re-open it when I close the second Qdialog, so this is what I tried but doesn't work:

c = conn.cursor()    
d = conndue.cursor()

class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__() # chiamare le inherited classi con metodo __init__
        uic.loadUi('pagina_scelta.ui', self) # caricare file.ui
        self.show() # mostrarlo
        bottonefinestramodifica = self.findChild(QtWidgets.QPushButton, 'bottone_modifica')
        bottonefinestramodifica.clicked.connect(self.finestramodifica)

    def finestramodifica(self):
        self.finestramodifica = modificaviaggi()
        self.finestramodifica.show()

class MyDelegate(QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        return         

class modificaviaggi(QtWidgets.QDialog):
    lastid = [0]
    recall = [2]
    def finestraarticoli(self):
        self.finestraarticoli = articoli()
        self.finestraarticoli.show()
    def chiusura(self):
        self.accept()
    def __init__(self):
        super(modificaviaggi, self).__init__()
        uic.loadUi('modifica_reg.ui', self)
        bottonetorna = self.bottone_torna
        bottonetorna.clicked.connect(self.chiusura)
        self.reloading()
        self.datitabella()
    def reloading(self):
        if 1 == 1:
            if self.recall[0] == 1:
                self.datitabella()
                self.recall[0] == 2
    def datitabella(self):    
        delegate = MyDelegate(self)
        tablerow = 0 
        conteggio = c.execute('SELECT COUNT(ID) FROM Viaggi').fetchone()[0]
        print(conteggio)
        customers = [" "]
        self.tabella_registrazioni.blockSignals(True)
        self.customers_combo(customers)   
        self.tabella_registrazioni.setRowCount(conteggio)
        for row in c.execute("SELECT * FROM Viaggi "):
            rigavalore = 0
            self.tabella_registrazioni.setRowCount(conteggio)
            for r in range(0, 19):
                self.tabella_registrazioni.setItem(tablerow, rigavalore, QtWidgets.QTableWidgetItem(str(row[rigavalore])))
                rigavalore+= 1
            tablerow+= 1
            self.combocreation(customers)
        self.combocreation(customers)
        self.tabella_registrazioni.blockSignals(False)   
        self.tabella_registrazioni.itemChanged.connect(self.changeIcon) 
        self.tabella_registrazioni.setItemDelegateForColumn(0, delegate)
        self.tabella_registrazioni.clicked.connect(self.pressed)
        self.combo_customers.activated.connect(self.customer_combo_selection)
        righe = self.tabella_registrazioni.rowCount()
        tablerow1= 0
        for i in range(0, righe):
            idrow = self.tabella_registrazioni.item(i, 0).text()
            netweight = c.execute("SELECT SUM(Peso_netto) FROM Pesi WHERE ID_registrazione = ?", idrow)
            if netweight != None or not netweight.isspace():
                netweight = float(str(netweight.fetchone()[0]))
            else:
                print("Nessun peso")
            grossweight = c.execute("SELECT SUM(Peso_lordo) FROM Pesi WHERE ID_registrazione = ?", idrow)
            if grossweight != None or not grossweight.isspace():
                grossweight = float(str(grossweight.fetchone()[0]))
            self.tabella_registrazioni.setItem(tablerow1, 8, QtWidgets.QTableWidgetItem(str(netweight)))
            self.tabella_registrazioni.setItem(tablerow1, 9, QtWidgets.QTableWidgetItem(str(grossweight)))
            tablerow1+= 1
    def combocreation(self, customers):
        self.combo_customers = QComboBox()
        self.combo_customers.setEditable(True)
    def customers_combo(self, customers):
        for cu in d.execute("SELECT ANDESCRI FROM VALL_CONTI WHERE ANTIPCON = 'C' "):
                customers.append(cu[0].strip())
    def changeIcon(self, item):
        row = item.row()
        col = item.column()
        zero = self.tabella_registrazioni.item(row, 0).text()
        uno =  self.tabella_registrazioni.item(row, 1).text()
        custcode = self.tabella_registrazioni.item(row, 3).text()
        custname = self.tabella_registrazioni.item(row, 4).text() 
        c.execute('UPDATE Viaggi SET Codice_cliente = ?, Ragione_sociale = ? WHERE ID = ?', 
                                                (custcode, custname, zero))
        c.commit()
    def pressed(self, item):
        row = item.row()
        col = item.column()
        customers = [" "]
        self.lastid[0] = self.tabella_registrazioni.item(row, 0).text()
        if col == 8 or col == 9:
            self.finestraarticoli()
        self.customers_combo(customers)   
        self.combocreation(customers)
        textcell = self.tabella_registrazioni.item(row, col).text()
        self.combo_customers.setCurrentText(textcell)
        self.combo_customers.activated.connect(self.customer_combo_selection)
        if col == 3:
            self.tabella_registrazioni.setCellWidget(row, 3, self.combo_customers)

    def customer_combo_selection(self):
        customer_name = self.combo_customers.currentText()
        row = self.rrow
        self.tabella_registrazioni.setItem(self.rrow, self.ccolumn, QtWidgets.QTableWidgetItem(str(customer_name)))
        id = self.tabella_registrazioni.item(row, 0).text()
        c.execute("UPDATE Viaggi SET Ragione_Sociale=? WHERE ID = ?", (customer_name, id))
        c.commit()

class articoli(QtWidgets.QDialog):
    def changevariable(self):
        modificaviaggi.recall[0] = 1
        self.accept()
    def __init__(self):
        super(articoli, self).__init__()
        uic.loadUi('Inserimento_articoli.ui', self)

        self.get_back_button.clicked.connect(self.changevariable)
        self.tabellapesi()
    def tabellapesi(self):
        self.IDpressed = modificaviaggi.lastid
        tablerow = 0 
        self.tabella_articoli.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        self.conteggio = int(str(c.execute("SELECT COUNT(ID_registrazione) FROM Pesi WHERE ID_registrazione = ? ", self.IDpressed[0]).fetchone()[0]))
        for row in c.execute("SELECT * FROM Pesi WHERE ID_registrazione = ? ORDER BY ID ", self.IDpressed[0]):
            rigavalore = 0
            self.tabella_articoli.setRowCount(self.conteggio)
            for r in range(0, 6):
                self.tabella_articoli.setItem(tablerow, rigavalore, QtWidgets.QTableWidgetItem(str(row[rigavalore])))
                rigavalore+= 1
            tablerow+= 1

    def insert(self):
        rows = self.tabella_articoli.rowCount()
        tablerow = 0
        for row in range (0, rows):
            articlecode = self.tabella_articoli.item(tablerow, 1).text()
            articledesc = self.tabella_articoli.item(tablerow, 2).text()
            netweight = float(self.tabella_articoli.item(tablerow, 3).text())
            grossweight  = float(self.tabella_articoli.item(tablerow, 4).text())
            price = float(self.tabella_articoli.item(tablerow, 5).text())
            if self.tabella_articoli.item(tablerow, 0) == None:
                IDweight = ""
            else:
                IDweight = int(self.tabella_articoli.item(tablerow, 0).text())
            queryinsert = "INSERT INTO Pesi ( Codice_articolo, Descrizione_articolo, Peso_netto, Peso_lordo, ID_registrazione, Prezzo) VALUES (?,?,?,?,?,?)"
            values = [articlecode, articledesc, netweight, grossweight, self.IDpressed[0], price]
            queryupdate = "UPDATE Pesi SET Peso_lordo = ?, Prezzo = ?, Peso_netto = ? , Codice_articolo = ?, Descrizione_articolo = ? WHERE ID = ? "
            valuesupdate = [grossweight, price, netweight, articlecode, articledesc, IDweight]           
            exist = str(c.execute("IF EXISTS (SELECT * FROM CARICO_VIAGGI..Pesi WHERE ID = ?) BEGIN SELECT 1 END ELSE BEGIN SELECT 2 END", (IDweight)).fetchone()[0])
            if exist == "1": 
                c.execute(queryupdate, valuesupdate)
                c.commit()
                print(type(IDweight))
            elif exist == "2":
                c.execute(queryinsert, values)
                c.commit()
            else:
                print("Impossibile salvare gli articoli, riprovare")
            tablerow+= 1
        self.tabella_articoli.clearContents()
        tablerow = 0 
        self.conteggiox = int(str(c.execute("SELECT COUNT(ID_registrazione) FROM Pesi WHERE ID_registrazione = ? ", self.IDpressed[0]).fetchone()[0]))
        for row in c.execute("SELECT * FROM Pesi WHERE ID_registrazione = ? ORDER BY ID", self.IDpressed[0]):
            rigavalore = 0
            self.tabella_articoli.setRowCount(self.conteggiox)
            for r in range(0, 6):
                self.tabella_articoli.setItem(tablerow, rigavalore, QtWidgets.QTableWidgetItem(str(row[rigavalore])))
                rigavalore+= 1
            tablerow+= 1

app = QtWidgets.QApplication(sys.argv) 
window = Ui() 
app.exec_() 



RE: Close and Open QDialog from QDialog 2 - Axel_Erfurt - Jul-11-2022

It's better to post a minimally reproducible example.


RE: Close and Open QDialog from QDialog 2 - ITSRL - Jul-11-2022

(Jul-11-2022, 03:06 PM)Axel_Erfurt Wrote: It's better to post a minimally reproducible example.
You're right but my code it's pretty long, I posted this cause I wanted to know if there were any mistakes in this portion of code, cause when I execute it doesn't return any errors, it just does nothing. I'll post more code by the way


RE: Close and Open QDialog from QDialog 2 - Axel_Erfurt - Jul-11-2022

A simple example to open dialog1 on closing dialog2

from PyQt5.QtWidgets import (QMainWindow, QApplication, 
                             QPushButton, QDialog)

class firstDialog(QDialog):
    def __init__(self, parent = None):
        super(firstDialog, self).__init__(parent)
        self.setGeometry(250, 250, 300, 100)
        self.setWindowTitle("Dialog 1")

       
class secondDialog(QDialog):
    def __init__(self, parent = None):
        super(secondDialog, self).__init__(parent)
        self.setGeometry(100, 100, 300, 100)
        self.setWindowTitle("Dialog 2")
                   
    def closeEvent(self, event):
        print("closing secondDialog\n\nopening firstDialog")
        self.firstdial= firstDialog()
        self.firstdial.show()
        event.accept()
            
class mainWin(QMainWindow):
    def __init__(self, parent = None):
        super(mainWin, self).__init__(parent)
        self.setupUI()
        
    def setupUI(self):
        self.setGeometry(0, 0, 400, 300)
        self.tb = self.addToolBar("TB")
        dialog_btn_1 = QPushButton("show Dialog")
        dialog_btn_1.clicked.connect(self.show_dlg)
        self.tb.addWidget(dialog_btn_1)

        
    def show_dlg(self):
        self.dlg = secondDialog()
        self.dlg.show()


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = mainWin()
    win.setWindowTitle("Main Window")
    win.show()

    sys.exit(app.exec_())



RE: Close and Open QDialog from QDialog 2 - ITSRL - Jul-12-2022

(Jul-11-2022, 03:06 PM)Axel_Erfurt Wrote: It's better to post a minimally reproducible example.
I posted it