QListWidget в PyQt5 - перемещение элемента вверх по списку при нажатии кнопки вверх - PullRequest
0 голосов
/ 19 марта 2020

У меня есть QListWidget в приложении pyQt5. Список содержит список предметов. Я выбираю определенный элемент, щелкая элемент в списке. После этого у меня есть QPushButton & Up , который должен сдвигать элемент вверх по списку, один раз при каждом нажатии, пока он не станет верхним элементом в списке. Когда я нажимаю кнопку - псевдокод, как показано ниже

get the row of the currently selected item
     if it is greater than row 1 then
         delete the item
         re insert the item at - (row - 1)
         set the newly inserted item as the current item
         **This should make the newly inserted item as the current 
           selected item with a blue band indicating selection**

Однако этого не произойдет, пока я не вызову метод перерисовки виджета списка.

self.__fruit_list - это QListWidget self.__button_up это QPushButton

Подключение слота определяется следующим образом:

self.__button_up.clicked.connect(self.__up)

Функция слота определяется следующим образом:

@pyqtSlot()
    def __up(self):
        """Move the item up by one row."""
        row = self.__fruit_list.currentRow()
        if row >= 1:
            # Remove the currently selected item.
            item = self.__fruit_list.takeItem(row)
            self.__fruit_list.insertItem(row - 1, item)
            self.__fruit_list.setCurrentItem(item)
            self.__fruit_list.repaint()

Почему я должен вызывать метод перекраски и почему список не обновляет sh автоматически? Есть ли способ, которым я могу сделать это без repaint () или что-то не так с моим подходом? Любые входные данные будут высоко оценены.

MRE Список программ minimalisti c *1023*

"""Demonstrates QListWidget and adding and modifying values using a dialog."""
# Importing the standard python libraries.
import sys

# Importing the PyQt5 libraries.
from PyQt5.QtWidgets import QApplication, QAbstractItemView, QMessageBox
from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtWidgets import QListWidget, QPushButton
from PyQt5.QtCore import pyqtSlot

class FruitListApp(QMainWindow):
    """Fruit List Management Application class."""

    def __init__(self, parent=None):
        """Initialize the Fruit List Application."""
        super().__init__(parent)

        # Setup the widgets.
        self.__fruit_list = QListWidget()
        self.__fruit_list.setSelectionMode(QAbstractItemView.SingleSelection)

        self.__button_up = QPushButton("&Up")

        # Layout the widgets.
        button_box = QWidget()
        button_box_layout = QVBoxLayout()
        button_box_layout.addWidget(self.__button_up)

        button_box.setLayout(button_box_layout)

        central_widget = QWidget()
        layout = QHBoxLayout()
        layout.addWidget(self.__fruit_list)
        layout.addWidget(button_box)

        central_widget.setLayout(layout)

        # Setup the main application window.
        self.setCentralWidget(central_widget)
        self.setWindowTitle("Edit Fruit List")

        # Setup signals and slots.
        self.__button_up.clicked.connect(self.__up)

    def add_items(self, item_list):
        """Add items provided as a list to the fruit list."""
        # Item is a list.
        if isinstance(item_list, list):
            if len(item_list) > 0:
                # Add items to the list after determining the previous count
                # of items in the list.
                previous_count = self.__fruit_list.count()
                self.__fruit_list.addItems(item_list)
                # Set the first item added from a list as the current
                # selection.
                self.__fruit_list.setCurrentRow(previous_count)
            else:
                QMessageBox.warning(self, "Error", "The fruit names list "
                                               "provided is empty.")
                return
        else:
            QMessageBox.warning(self, "Error", "The fruit names are not "
                                               "provided as a list.")
            return

    @pyqtSlot()
    def __up(self):
        """Move the item up by one row."""
        row = self.__fruit_list.currentRow()
        if row >= 1:
            # Remove the currently selected item.
            item = self.__fruit_list.takeItem(row)
            self.__fruit_list.insertItem(row - 1, item)
            self.__fruit_list.setCurrentItem(item)
            self.__fruit_list.repaint()

if __name__ == "__main__":

    def main():
        """Main method to test the application."""
        # The fruit list.
        fruit = ["Banana", "Apple", "Elderberry", "Clementine", "Fig", "Guava",
                 "Mango", "Honeydew Melon", "Date", "Watermelon", "Tangerine",
                 "Ugli Fruit", "Juniperberry", "Kiwi", "Lemon", "Nectarine",
                 "Plum", "Raspberry", "Strawberry", "Orange"]

        # Instantiate the application.
        app = QApplication(sys.argv)

        # Instantiate the Fruit List Main Window.
        main_window = FruitListApp()
        # Add the fruit list.
        main_window.add_items(fruit)

        # Display the main application window.
        main_window.show()

        # Start the event loop.
        app.exec_()

    # Start the application.
    main()

** Прокомментируйте следующую строку, чтобы воспроизвести проблему. ** self.__fruit_list.repaint()

...