Search code examples
pythonpyqt4qlistwidget

Enable a single selection between 2 Lists


I am encountering this problem, and I hope someone can help me.

I am trying to create a situation where there are 2 QListWidgets, List01 and List02 for example, and they contains the following.

List01 = [T01, T02, T03]
List02 = [P01, P02, P03]

I wanted the user to select an item (T01) in List01, and hence in List02, no selection (highlighting) of any items will be conducted, meaning to say if the user hovers over to List02 and selects an item (P02), the selection in List01 will be gone and it will be the item (P02) selected in List02.

Currently, I am getting the problem, where my program is able to select an item in the 2 lists and I am not sure how to perform the above.

Could someone kindly guide me? Many thanks in advance


Solution

  • OK here is an example code of how could you do what you want, it's very basic but you can get the idea within the functions f and g, hope it works:

    import PyQt4.QtGui as gui
    
    
    app = gui.QApplication([]) 
    
    
    w = gui.QWidget()
    l = gui.QHBoxLayout(w)
    w.setLayout(l)
    
    lis1 = gui.QListWidget()
    lis2 = gui.QListWidget()
    
    lis1.addItems(["1","2","3"])
    lis2.addItems(["4","5","6"])
    
    def f():    
        lis2.itemSelectionChanged.disconnect(g)    
        for item in lis2.selectedItems():
            lis2.setItemSelected(item,False)
        lis2.itemSelectionChanged.connect(g)
    
    
    def g():
        lis1.itemSelectionChanged.disconnect(f)    
        for item in lis1.selectedItems():
            lis1.setItemSelected(item,False)    
        lis1.itemSelectionChanged.connect(f)
    
    
    print dir(lis1.itemSelectionChanged)
    
    lis1.itemSelectionChanged.connect(f)
    lis2.itemSelectionChanged.connect(g)
    
    l.addWidget(lis1)
    l.addWidget(lis2)
    
    w.show()
    
    
    app.exec_()