Как выбрать элемент из Qlistwidget и обновить текстовое поле в Pyqt5?

#python #pyqt5

#python #pyqt5

Вопрос:

Выберите элемент из QListWidget с помощью клавиатуры (событие нажатия клавиши), работает отлично.

Но в то же время я хочу также выбрать элемент из QListWidget щелчком мыши.

попробуйте использовать «itemclicked.connect», но это работает не так, как я ожидал.

Мой код здесь :

Файл 1 (имя файла: example_main_001.py ):

    import sys
    
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import  *
    from PyQt5.QtGui import *
    
    from example_source_file_001 import Sourcefile
    
    textbox_items = {
        "textbox1": ["Python", "Python 2.7", "Python 2.9", "Python 3.5", "Python 3.7", "National", "Zebra",
                     "Apple", "X Ray", "Boat", "Tiger", "Item001", "Item002", "Item003", "Item004", "Item005",
                     "001Item", "002Item", "003Item", "004Item", "005Item", "Ball", "Cat", "Dog", "Fish",
                     "Gold Fish", "Star Fish", "2821", "2822", "2823", "2811", "2812", "2813"],
    
        "textbox2": ["India","America","Russia","China","England","Iran","Iraq","Ice Land"],
    
        "textbox3": ["Red", "Dark red", "Light Red", "Redish Blue", "Redish Green", "Green","Blue","Dark 
 Blue", "Dark Green"]
        }
    
    
    class Mclick_sample_main(QWidget):
        def __init__(self):
            super().__init__()
    
            self.setWindowTitle("Mouse click Samples")
            self.textbox1 = QLineEdit()
            self.textbox2 = QLineEdit()
            self.textbox3 = QLineEdit()
            self.lbox1 = QListWidget()
            self.lbox2 = QListWidget()
    
            self.textbox1.setObjectName("textbox1")
            self.textbox2.setObjectName("textbox2")
            self.textbox3.setObjectName("textbox3")
            self.lbox1.setObjectName("listbox1")
            self.lbox2.setObjectName("listbox2")
    
            vbox = QVBoxLayout(self)
            vbox.addWidget(self.textbox1)
            vbox.addWidget(self.textbox2)
            vbox.addWidget(self.textbox3)
            vbox.addWidget(self.lbox2)
    
            self.current_textbox = None
            QApplication.instance().focusChanged.connect(self.on_focusChanged)
    
            self.textbox1.returnPressed.connect(lambda: self.textbox2.setFocus(Qt.ShortcutFocusReason))
            self.textbox2.returnPressed.connect(lambda: self.textbox3.setFocus(Qt.ShortcutFocusReason))
            self.textbox3.returnPressed.connect(lambda: self.textbox1.setFocus(Qt.ShortcutFocusReason))
    
        def on_focusChanged(self, old, new):
            fwidget = QApplication.focusWidget()
            if fwidget is not None:
    
                if isinstance(new, QLineEdit) and new != self.current_textbox:
                    self.current_textbox = new
                    self.lbox1.clear()
                    self.lbox1.addItems(textbox_items[new.objectName()])
                    self.lbox2.clear()
                    self.lbox2.addItems(textbox_items[new.objectName()])
    
                    self.getdetails_1 = Sourcefile(self.current_textbox, self.lbox1, self.lbox2)
                    self.current_textbox.textChanged.connect(self.getdetails_1.func_textbox_textchanged)
    
    def main():
        myapp = QApplication(sys.argv)
        mywin = Mclick_sample_main()
        mywin.show()
        sys.exit(myapp.exec_())
    
    
    if __name__ == "__main__":
        main()
 

Файл 2 (Имя файла : example_source_file_001.py )

 from PyQt5.QtWidgets import *
from PyQt5.QtGui import  *
from PyQt5.QtCore import *

flag = 1
search_text_length = 0
startitem_rowno = None
enditem_rowno = None
selected_item = None
selec_item = None


class Sourcefile(QWidget):
    def __init__(self, textbox, listbox1,listbox2,parent=None):
        super().__init__(listbox2)
        global startitem_rowno,enditem_rowno

        self.setFocusPolicy(Qt.StrongFocus)
        self.tbox1 = textbox
        self.lbox1 = listbox1
        self.lbox2 = listbox2

        self.tbox1.installEventFilter(self)
        self.lbox2.installEventFilter(self)

        startitem_rowno = 0
        enditem_rowno = len(self.lbox2) - 1



    def eventFilter(self, source, event):
        global cursor_position, textbox_value,selected_item


        if event.type() == QEvent.KeyPress and source is self.tbox1:

            if event.modifiers() == Qt.AltModifier and event.key() == Qt.Key_S:
                self.func_item_startswith()
                return True

            if event.key() == Qt.Key_Down:
                self.lbox2.setFocus()
                self.lbox2.setCurrentRow(startitem_rowno)
                cursor_position = self.tbox1.cursorPosition()
                textbox_value = self.tbox1.text()


            if event.key() == Qt.Key_Up:
                self.lbox2.setFocus()
                self.lbox2.setCurrentRow(enditem_rowno)
                cursor_position = self.tbox1.cursorPosition()
                textbox_value = self.tbox1.text()

            if event.key() == Qt.Key_Return:
                pass



        if event.type() == QEvent.KeyPress and source is self.lbox2:

            if event.key() == Qt.Key_Left or event.key() == Qt.Key_Backspace:
                self.tbox1.setFocus()
                return True

            elif event.key() == Qt.Key_Return :
                self.selected_item = self.lbox2.currentItem().text()

                if self.selected_item is not None:
                    self.tbox1.setText(self.selected_item)
                    self.tbox1.setFocus()
                    return True
            elif event.key() == Qt.Key_Up or event.key() == Qt.Key_Down:
                pass
        return super(Sourcefile, self).eventFilter(source, event)

    def func_item_startswith(self):

        global flag, startitem_rowno, enditem_rowno
        flag = 1
        startitem_rowno = 0
        enditem_rowno = startitem_count - 1
        # self.lbox2.clear()

        if startitem_count > 0:
            for item in item_startswith:
                self.lbox2.addItem(item.text())
        else:
            print("No Matching from start item")

    def func_item_normal(self):
        global falg,startitem_rowno,enditem_rowno
        flag = 0
        startitem_rowno = 0
        enditem_rowno = normal_count - 1

        self.lbox2.clear()

        if normal_count > 0:
            for item in item_normal:
                self.lbox2.addItem(item.text())

    def func_textbox_textchanged(self, txt):

        global search_text, search_text_length, total_listbox_item, availableitem_count, normal_count, startitem_count, 
            containitem_count, enditem_count, item_normal, item_startswith, item_contains, item_endswith, flag, 
            startitem_rowno, enditem_rowno

        search_text = self.tbox1.text()

        search_text_length = len(search_text)
        total_listbox_item = len(self.lbox2)

        item_normal = self.lbox1.findItems("*", Qt.MatchWildcard)
        item_startswith = self.lbox1.findItems(search_text, Qt.MatchStartsWith)

        normal_count = len(item_normal)
        startitem_count = len(item_startswith)

        self.func_item_normal()

        if search_text_length >= 1: pass
        else: flag = 1

        self.lbox2.clear()


        if flag == 1:

            self.func_item_startswith()
        else:
            self.func_item_normal()
 

Ответ №1:

Извините, я не совсем понял ваш пример, но я попытался добавить itemClicked.connect . Я отметил строки, в которые внес изменения. Попробуйте:

example_main_001.py

 import sys

from PyQt5.QtWidgets import *
from PyQt5.QtCore import  *
from PyQt5.QtGui import *

from example_source_file_001 import Sourcefile

textbox_items = {
    "textbox1": ["Python", "Python 2.7", "Python 2.9", "Python 3.5", "Python 3.7", "National", "Zebra",
                 "Apple", "X Ray", "Boat", "Tiger", "Item001", "Item002", "Item003", "Item004", "Item005",
                 "001Item", "002Item", "003Item", "004Item", "005Item", "Ball", "Cat", "Dog", "Fish",
                 "Gold Fish", "Star Fish", "2821", "2822", "2823", "2811", "2812", "2813"],

    "textbox2": ["India","America","Russia","China","England","Iran","Iraq","Ice Land"],

    "textbox3": ["Red", "Dark red", "Light Red", "Redish Blue", "Redish Green", "Green","Blue",
                 "Dark Blue", "Dark Green"]
    }


class ListWidget(QListWidget):                                               #    
    def __init__(self, parent=None):                                         #    
        super(ListWidget, self).__init__(parent)                             #    
        
    def _clicked(self, item):                                                #    
        self.window().old.setText(item.text())                               #    
        

class Mclick_sample_main(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Mouse click Samples")
        self.textbox1 = QLineEdit()
        self.textbox2 = QLineEdit()
        self.textbox3 = QLineEdit()
        self.lbox1 = QListWidget()

        self.old, self.new = None, None                                      #     
#        self.lbox2 = QListWidget()                                          # ---
        self.lbox2 = ListWidget(self)                                        #     
        self.lbox2.itemClicked.connect(self.lbox2._clicked)                  #    

        self.textbox1.setObjectName("textbox1")
        self.textbox2.setObjectName("textbox2")
        self.textbox3.setObjectName("textbox3")
        self.lbox1.setObjectName("listbox1")
        self.lbox2.setObjectName("listbox2")

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.textbox1)
        vbox.addWidget(self.textbox2)
        vbox.addWidget(self.textbox3)
        vbox.addWidget(self.lbox2)

        self.current_textbox = None
        QApplication.instance().focusChanged.connect(self.on_focusChanged)

        self.textbox1.returnPressed.connect(lambda: self.textbox2.setFocus(Qt.ShortcutFocusReason))
        self.textbox2.returnPressed.connect(lambda: self.textbox3.setFocus(Qt.ShortcutFocusReason))
        self.textbox3.returnPressed.connect(lambda: self.textbox1.setFocus(Qt.ShortcutFocusReason))

    def on_focusChanged(self, old, new):
        fwidget = QApplication.focusWidget()
        
        self.old, self.new = old, new                                        #    
        
        if fwidget is not None:

            if isinstance(new, QLineEdit) and new != self.current_textbox:
                self.current_textbox = new
                self.lbox1.clear()
                self.lbox1.addItems(textbox_items[new.objectName()])
                self.lbox2.clear()
                self.lbox2.addItems(textbox_items[new.objectName()])

                self.getdetails_1 = Sourcefile(self.current_textbox, self.lbox1, self.lbox2)
                self.current_textbox.textChanged.connect(self.getdetails_1.func_textbox_textchanged)


def main():
    myapp = QApplication(sys.argv)
    mywin = Mclick_sample_main()
    mywin.show()
    sys.exit(myapp.exec_())


if __name__ == "__main__":
    main()
    
 

введите описание изображения здесь

Комментарии:

1. Спасибо. Ваш код идеален, как мне нужно. Большое вам спасибо