Search code examples
pythonpyqt5qlistwidgetqlistwidgetitem

itemClicked in QlistWidget, function executed more than 1 time


I have a strange problem, hope someone can clear it for me

import os
from os import path
import sys
import pathlib
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, 
QWizard, QWizardPage, QLineEdit, \
                        QTabWidget, QApplication, 
QTextEdit,QToolTip,QPushButton,QMessageBox
from PyQt5.QtCore import QSize,pyqtSlot,pyqtProperty
from PyQt5.QtGui import QFont
from PyQt5.uic import loadUiType

app = QApplication(sys.argv)

if getattr(sys, 'frozen', False):
    # we are running in a bundle
    installPath = sys._MEIPASS
    print('we are running in a bundle')
else:
    # we are running in a normal Python environment
    installPath = os.path.dirname(os.path.abspath(__file__))
    print('we are running in a normal Python environment')

UI_File, _ = loadUiType(path.join(path.dirname(__file__), 'test.ui'))

class MainAPP(QTabWidget, UI_File):
    def __init__(self, parent=None):
        super(MainAPP, self).__init__(parent)
        self.setupUi(self)
        self.handle_buttons()
    def handle_buttons(self):
        self.pushButton.clicked.connect(self.test_2)
    def test_2(self):
        for i in range(10):
            self.listWidget.addItem(str('lklk'))
        self.listWidget.itemClicked.connect(self.test)
    def test(self):
        for i in range(10):
            self.listWidget_2.addItem(str('DDD'))
        self.listWidget_2.itemClicked.connect(self.test_3)
    def test_3(self):
            print ('hi')
def main():
    app = QApplication(sys.argv)
    main = MainAPP()
    main.show()
    app.exec_()

if __name__ == "__main__":
    main()

so basically, I have a push button, if I click on it it will display some data at listWidget and if I clicked on any item in listWidget , it will display other data on ListWidget_2 and then if I click on item in List_widget_2 it then should print ('Hi')

the problem is if I click multiple times in ListWidget and then click on an item in ListWidget_2 , I received more than one ('Hi) , it will diplay ('Hi') according to the number of clicks I clicked in the Listwidget

any idea what could be the issue


Solution

  • You only need to make a connection between a signal and a slot once. Currently you are making additional connections each time you click an item in the first list widget, which results in your method printing "hi" executing once for every connection you made.

    To fix this, make both of the signal connections either in the test_2 method or in the __init__ method