Python Forum
Close and Open QDialog from QDialog 2
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Close and Open QDialog from QDialog 2
#1
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_() 
Larz60+ write Jul-11-2022, 02:50 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts
Reply
#2
It's better to post a minimally reproducible example.
Reply
#3
(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
Reply
#4
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_())
Reply
#5
(Jul-11-2022, 03:06 PM)Axel_Erfurt Wrote: It's better to post a minimally reproducible example.
I posted it
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How To Find an Opening and Closing String, Copying Open/Close/Contents to New File davidshq 1 2,027 Mar-03-2020, 04:47 AM
Last Post: davidshq
  How can I Open and close .py file from python scripts SayHiii 9 5,732 Dec-17-2019, 06:10 AM
Last Post: Malt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020