Bonjour,

Je suis confronté à un problème de gestion de mes QComboBox en cascade. J'ai un QLineEdit et cinq QCombobox.
Je saisi dans un premier temps une valeur dans mon QLineEdit() pour définir l'alimentation des mes QComboBox.
Je sélectionne une valeur dans la première qui va me définir l'alimentation de ma deuxième et ainsi de suite...

Jusque là l'alimentation en cascade se déroule parfaitement, sauf dans le cas où je saisi une nouvelle valeur dans mon QLineEdit(). Lorsque je valide cette dernière mon application se ferme et je ne sais pas d'où cela peut provenir...

Pour remettre à zéro mes QComboBox j'utilise la fonction *.clear(), je pensais que le problème pouvais venir de là mais non...

Si quelqu'un à déjà était confronté à ce genre de problème...

Je mets mon code en complément pour que vous puissiez voir ma méthodes d'alimentation qui n'est je pense pas la meilleur

Merci par avance.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import sys, os
import sqlite3
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QDateTimeEdit,
        QDial, QDialog, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit,
        QProgressBar, QPushButton, QRadioButton, QScrollBar, QSizePolicy, QTableWidgetItem,
        QSlider, QSpinBox, QStyleFactory, QTableWidget, QTabWidget, QTextEdit,
        QVBoxLayout, QWidget, QMainWindow, QFrame, QFormLayout, QMessageBox)
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import pyqtSlot, QSettings, QDateTime, Qt, QTimer, QDateTime
from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtSql import QSqlDatabase
import logging
from logging.handlers import RotatingFileHandler
 
 
class App(QMainWindow):
    #===============================================================================================
    def __init__(self, parent=None):
        super(App, self).__init__(parent)
        #--- Application datas ---------------------------------------------------------------------
        settings=QSettings('ini/application.ini',QSettings.IniFormat);
        global APPLICATION_NAME
        APPLICATION_NAME=settings.value("GLOBAL_PARAMETERS/APPLICATION_NAME")
        self.setFont(QtGui.QFont('Courier new', 10))   
        self.setWindowIcon(QIcon('ini/graph.ico'))
        self.setWindowTitle(APPLICATION_NAME+ " - Design By.")
 
        #--- Logfile -------------------------------------------------------------------------------
        if not os.path.isdir('logfile'):
            os.mkdir('logfile')
 
        #--- Creation of objet logger which be used to write into logs -----------------------------
        self.logger = logging.getLogger()
 
        #--- Level logger at DEBUG, like that he writes all ----------------------------------------
        self.logger.setLevel(logging.DEBUG)
 
        #--- Creation of formater which add time,
        #--- level of each messsage when we will write a message into logfile. ---------------------
        self.formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
 
        #--- Creation of handler which redirect a write of log to a file
        #--- in 'append mode' with one backup and a size of 1Mo. -----------------------------------
        self.file_handler = RotatingFileHandler('logfile/'+os.getlogin()+'_'+APPLICATION_NAME+'.log', 'a', 1000000, 1)
 
        #--- DEBUG level assigned, logger must used the last formater created previously
        #--- and add this handle to logger. --------------------------------------------------------
        self.file_handler.setLevel(logging.DEBUG)
        self.file_handler.setFormatter(self.formatter)
        self.logger.addHandler(self.file_handler)
 
        #--- Creation of a seconf handler which redirect each log write on console. ----------------
        self.stream_handler = logging.StreamHandler()
        self.stream_handler.setLevel(logging.DEBUG)
        self.logger.addHandler(self.stream_handler)
        #--- End of logfile parameters -------------------------------------------------------------
        self.logger.log(logging.INFO, os.getlogin()+' start '+APPLICATION_NAME+'.')
 
        self.dbconnexion   = sqlite3.connect('sql/GMAO.db')
        self.cursor        = self.dbconnexion.cursor()
 
        self.initUI()
    #===============================================================================================
 
    def initUI(self):
 
        #--- User Interface ------------------------------------------------------------------------
        #--- Header --------------------------------------------------------------------------------
        Headband = QPixmap('ini/bandeau.jpg')
        self.bandeau   = QLabel(self)
        self.bandeau.setFixedHeight(15)
        self.bandeau.setScaledContents(True)
        self.bandeau.setPixmap(Headband)
 
        #--- QTabWidget creation with x tabwidget --------------------------------------------------
        self.tabwidget = QTabWidget(self)
        self.tabwidget.addTab(self.tab1(), "Saisie panne et consultation")
        self.tabwidget.addTab(self.tab2(), "Réparation")
        self.tabwidget.addTab(self.tab3(), "Tabwidget 3")
        self.tabwidget.addTab(self.tab4(), "Administration")
        self.tabwidget.currentChanged.connect(self.onChange)
 
        self.setCentralWidget(QFrame())
        layout = QGridLayout()
        layout.addWidget(self.bandeau, 0, 0)
        layout.addWidget(self.CreateToolInformationFormGroup(), 1, 0)
        layout.addWidget(self.tabwidget, 2, 0)
        #self.tabwidget.setDisabled(True)
        self.centralWidget().setLayout(layout)
 
        #--- Affichage d'un message sur la barre de status -----------------------------------------
        self.statusBar().showMessage(os.getlogin()+' is currently connected.')
 
    def onChange(self):
        self.logger.log(logging.INFO,str(os.getlogin())+' select self.tab1('+str(self.tabwidget.currentIndex())+')')
 
    def CreateToolInformationFormGroup(self):
        #--- QGroupBox below header ----------------------------------------------------------------
        groupBox = QGroupBox("--- Saisie et informations outillage ---")
        self.label_1 = QLabel()
        self.label_1.setText("Saisir le numéro de l'outillage:")
        self.toolQRcode = QLineEdit(self)
        self.toolQRcode.textChanged.connect(self.to_upper)
        self.toolQRcode.setFixedWidth(200)
        self.toolQRcode.setMaxLength(8)
        self.toolQRcode.returnPressed.connect(self.onPressed)
        self.label_ToolInformations = QLabel()
        self.label_ToolInformations.setText("")
 
        vbox = QVBoxLayout()
        vbox.addWidget(self.label_1)
        vbox.addWidget(self.toolQRcode)
        vbox.addWidget(self.label_ToolInformations)
        #vbox.addStretch(1)
        groupBox.setLayout(vbox)
        return groupBox
 
    #--- QLineEdit in Uppercase --------------------------------------------------------------------
    def to_upper(self, txt):
        self.toolQRcode.setText(txt.upper()) 
 
    #--- Function after onPressed QLineEdit --------------------------------------------------------
    def onPressed(self):
        #self.label_ToolInformations.setText(self.toolQRcode.text())
        self.logger.log(logging.INFO, os.getlogin()+' entered '+self.toolQRcode.text()+'.')
 
        #--- Check is tool number is correctly enterd e.g SINO0001 ---------------------------------
        if len(self.toolQRcode.text()) < 8:
            QMessageBox().critical(self, APPLICATION_NAME, "Le numéro de l'outillage doit faire 8 caractères! (exemple: SINO0001)", QMessageBox.Ok)
            #self.tabwidget.setDisabled(True)
        elif not self.toolQRcode.text()[4:].isdigit():
            QMessageBox().critical(self, APPLICATION_NAME, "Les 4 derniers digits doivent être décimal.", QMessageBox.Ok)
        elif not self.toolQRcode.text()[:4].isalpha():
            QMessageBox().critical(self, APPLICATION_NAME, "Les 4 premiers digits ne doivent pas être décimal.", QMessageBox.Ok)    
        else:
            self.label_ToolInformations.setText(self.toolQRcode.text())
            #--- Clear Combobox --------------------------------------------------------------------
            #self.ComboIntervenant.clear()
            #self.ComboLine.clear()
            #self.ComboCell.clear()
 
            #--- Query to check if tool number is registered ---------------------------------------
            try:
                #self.dbconnexion  = sqlite3.connect('sql/GMAO.db')
                #self.cursor       = self.dbconnexion.cursor()
                self.cursor.execute("SELECT * FROM idtools WHERE QR_TOOL ='"+self.toolQRcode.text()+"';")
                self.idtools_rows = self.cursor.fetchone()
 
                if self.idtools_rows == None:
                    #self.tabwidget.setDisabled(True)
                    self.label_ToolInformations.setText('L\'outillage '+self.toolQRcode.text()+ ' n\'existe pas.')
                    self.logger.log(logging.WARNING, 'L\'outillage '+self.toolQRcode.text()+ ' n\'existe pas.')
                    self.buttonReply = QMessageBox.warning(self, APPLICATION_NAME, "L\'outillage "+self.toolQRcode.text()+ " n\'existe pas. Voulez-vous le créer?" , QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                    if self.buttonReply == QMessageBox.Yes:
                        QMessageBox().critical(self, APPLICATION_NAME, "Vous n'êtes pas autorisé pour cette action.", QMessageBox.Ok)
                    else:
                        print('No clicked.')
                else:             
                    self.tabwidget.setDisabled(False)
                    self.cursor.execute("SELECT * FROM idtools WHERE QR_TOOL ='"+self.toolQRcode.text()+"';")
                    self.idtools_rows = self.cursor.fetchall()
                    global tooldata
                    self.tooldata = []
 
                    for row in self.idtools_rows:
                        self.tooldata.append(row)
 
                    self.label_ToolInformations.setText(self.tooldata[0][6]+' '+self.tooldata[0][9])
                    self.LoadIntervenant()
                    #self.LoadLines()
 
            except sqlite3.Error:
                self.logger.log(logging.WARNING,"onPressed(self) -> Error with database connexion")
 
    #--- Tabwidget 1 -------------------------------------------------------------------------------             
    def tab1(self):
        Tab1 = QWidget(self)
        Tab1layout = QVBoxLayout(Tab1)
        #--- Label, QComboBox definition... -------------------------------------------------------- 
        self.label_1 = QLabel("Intervenant:")
        self.ComboIntervenant = QComboBox(self)
 
        #---/
        self.label_2 = QLabel("Ligne:")
        self.ComboLine = QComboBox(self)
 
        #---/
        self.label_3 = QLabel("Cellule:")
        self.ComboCell = QComboBox(self)
 
        #---/
        self.label_4 = QLabel("Emplacement sur cellule:")
        self.ComboToollocation = QComboBox(self)
 
        #---/
        self.label_5 = QLabel("Outillage mis en place:")
        self.ComboToolIn = QComboBox(self)
 
        #---/
        self.label_6 = QLabel("Date du retrait:")
 
        #---/
        self.label_7 = QLabel("Commentaire(s):")
        self.commentaire = QTextEdit(self)
 
        #---/
        self.Tab1ButtonValidation = QPushButton('Valider la saisie')
        self.Tab1ButtonToPDF = QPushButton('Imprimer au format pdf')
 
        #---/
        self.label_8 = QLabel("")
        self.label_9 = QLabel("")
        self.label_10 = QLabel("")
        self.label_11 = QLabel("")
        self.label_12 = QLabel("")
        self.label_13 = QLabel("")
        self.label_14 = QLabel("")
        self.label_15 = QLabel("")
        self.label_16 = QLabel("")
        self.label_17 = QLabel("")
        self.label_18 = QLabel("")
        self.label_19 = QLabel("")
        self.label_20 = QLabel("")
 
        #---/
        self.dateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime(), self)
        self.dateTimeEdit.setDisplayFormat("dd/MM/yyyy HH:mm")
 
        #--- QGroupBox left tab1 -------------------------------------------------------------------
        self.groupBoxTab1_1 = QGroupBox("--- Renseignements panne outillage ---", Tab1)
        Tab1layout.addWidget(self.groupBoxTab1_1)
 
        #---/    
        layout = QGridLayout() 
        layout.addWidget(self.label_1, 0, 0)
        layout.addWidget(self.ComboIntervenant, 0, 1)
        layout.addWidget(self.label_2, 1, 0)
        layout.addWidget(self.ComboLine, 1, 1)
        layout.addWidget(self.label_3, 2, 0)
        layout.addWidget(self.ComboCell, 2, 1)
        layout.addWidget(self.label_4, 3, 0)
        layout.addWidget(self.ComboToollocation, 3, 1)
        layout.addWidget(self.label_5, 4, 0)
        layout.addWidget(self.ComboToolIn, 4, 1)
        layout.addWidget(self.label_6, 0, 3)
        layout.addWidget(self.dateTimeEdit, 1, 3)
        layout.addWidget(self.label_7, 2, 3)
        layout.addWidget(self.commentaire, 3, 3, 2, 3)
        #layout.addWidget(self.label_8, 0, 5)
        #layout.addWidget(self.label_9, 0, 6)
        #layout.addWidget(self.label_10, 0, 7)
        #layout.addWidget(self.label_11, 0, 8)
        #layout.addWidget(self.label_12, 0, 9)
        #layout.addWidget(self.label_13, 0, 10)
        #layout.addWidget(self.label_14, 0, 11)
        #layout.addWidget(self.label_15, 0, 12)
        layout.addWidget(self.label_16, 5, 0)
        layout.addWidget(self.label_17, 6, 0)
        layout.addWidget(self.label_18, 7, 0)
        #layout.addWidget(self.label_19, 8, 0)
        #layout.addWidget(self.label_20, 9, 0)
 
        #---/Buttons validation & pdf
        layout.addWidget(self.Tab1ButtonValidation, 6, 6)
        layout.addWidget(self.Tab1ButtonToPDF, 7, 6)
 
        #---/
        self.groupBoxTab1_1.setLayout(layout)
 
        #--- QGroupBox right tab1 ------------------------------------------------------------------
        self.groupBoxTab1_2 = QGroupBox("--- Historique outillage ---", Tab1)
        Tab1layout.addWidget(self.groupBoxTab1_2)
 
        #--- QTableWidget on tab1 ------------------------------------------------------------------
        #tab1 = QWidget()
        tableWidget = QTableWidget(self)
        tableWidget.setColumnCount(10)
        tableWidget.setRowCount(1)
        tableWidget.setHorizontalHeaderLabels(["ID tool", "Date", "Ligne", "Cellule", "Position", "Intervenant", "Consultation", "Etat", "Modifier", "Supprimer"])
 
        #--- I have to do a query according the QRTool to know if there is some result or not ------
 
        row=0
        data = ['']
        for item in data:
            cellinfo=QTableWidgetItem(item)
            ComboBreakdown = QtWidgets.QComboBox()
            ComboBreakdown.addItem("Choix")
            ComboBreakdown.addItem("Modifier panne")
            ComboBreakdown.addItem("Modifier réparation")
            tableWidget.setItem(row, 0, cellinfo)
            tableWidget.setCellWidget(row, 8, ComboBreakdown)
            #---/
            ComboReparation = QtWidgets.QComboBox()
            ComboReparation.addItem("Choix")
            ComboReparation.addItem("Supprimer panne")
            ComboReparation.addItem("Supprimer réparation")
            tableWidget.setItem(row, 0, cellinfo)
            tableWidget.setCellWidget(row, 9, ComboReparation)
 
            row += 1
 
        tableWidget.resizeColumnsToContents()
        tab1hbox = QHBoxLayout()
        tab1hbox.addWidget(tableWidget)
 
        #---/
        self.groupBoxTab1_2.setLayout(tab1hbox)
 
        return Tab1
 
    #--- Tabwidget 2 -------------------------------------------------------------------------------      
    def tab2(self):
        groupBoxTab2 = QGroupBox("--- Tabwidget 2 ---")
        return groupBoxTab2
 
    #--- Tabwidget 3 -------------------------------------------------------------------------------      
    def tab3(self):
        groupBoxTab3 = QGroupBox("--- Tabwidget 3 ---")
        return groupBoxTab3
 
    #--- Tabwidget 4 -------------------------------------------------------------------------------      
    def tab4(self):
        groupBoxTab4 = QGroupBox("--- Tabwidget 4 ---")
        return groupBoxTab4
 
    #--- Here all queries to fill Combobox ---------------------------------------------------------
 
    #--- Intervenant -------------------------------------------------------------------------------
    def LoadIntervenant(self):
        #self.ComboIntervenant.clear()
        try:    
            #--- ComboBox ComboIntervenant ---
            self.cursor        = self.dbconnexion.cursor()
            self.cursor.execute("SELECT * FROM intervenant;")
            self.idintervenant = self.cursor.fetchall()         
 
            for i in self.idintervenant:
                self.ComboIntervenant.addItem(i[2]+' '+i[1])
 
            self.ComboIntervenant.setCurrentIndex(-1)
            self.ComboIntervenant.currentIndexChanged.connect(self.LoadLines)
 
        except sqlite3.Error:
            self.logger.log(logging.WARNING, "LoadIntervenant(self) -> Error with database connexion")
 
    #--- Load lines --------------------------------------------------------------------------------
    def LoadLines(self):    
        try:
            self.cursor.execute("SELECT * FROM lines;")
            self.idlines = self.cursor.fetchall()
 
            for j in self.idlines:
                self.ComboLine.addItem(j[1])
 
            self.ComboLine.setCurrentIndex(-1)
            self.ComboLine.currentIndexChanged.connect(self.CascadeCellsFilling)
 
        except sqlite3.Error:
            self.logger.log(logging.WARNING, "LoadLines(self) - > Error with database connexion")
 
    #--- Load cells according tool -----------------------------------------------------------------       
    def CascadeCellsFilling(self):
        #--- Fill all the other ComboBox according previous choices ---
        #self.ComboCell.clear()
        #self.ComboToollocation.clear()
        try:
            self.cursor.execute("SELECT * FROM lines WHERE LINE_SHORT_NAME = '"+self.ComboLine.currentText()+"';")
            self.idline = self.cursor.fetchall()
 
            #self.ComboCell.clear()
            #self.ComboToollocation.clear()
            #self.ComboToolIn.clear()
            global tooltype, idtool, line_id
            self.tooltype = self.tooldata[0][0]
            self.idtool   = self.tooldata[0][8]
            self.line_id  = self.idline[0][0]
 
            #--- Get associated cells according tool --- 
            self.cursor.execute("SELECT distinct(ID_CELL), lines.ID, CELL_NUMBER, CELL_NAME FROM location, lines, cells	WHERE location.ID_TOOL='"+str(self.idtool)+"' AND cells.ID=location.ID_CELL AND lines.ID=cells.ID_LINE AND lines.ID= '"+str(self.line_id)+"';")
            self.cells = self.cursor.fetchall()
 
            global AttachedCells
            self.AttachedCells = []
 
            for k in self.cells:
                self.AttachedCells.append(k)
                self.ComboCell.addItem(str(k[2])+' '+str(k[3]))
 
            self.ComboCell.setCurrentIndex(-1)
            #self.ComboCell.currentIndexChanged.connect(self.CascadeLocationFilling)
 
        except sqlite3.Error:
            self.logger.log(logging.WARNING, "CascadeCellsFilling(self) -> Error with database connexion")
 
 
 
 
 
#--- /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ---         
#--- /!\ --- DO NOT DELETE BELOW ---- /!\ ----------------------------------------------------------
#--- /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ------ /!\ ---            
if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    ex = App()
    ex.showMaximized()
    sys.exit(app.exec_())