首页 > 解决方案 > QListWidget:currentRowChanged 回滚

问题描述

def selected_radio_connection_changed(self,current_row):
    self.current_row_new = self.main_self.ui_edit_radio_stations_window.stations_list.currentRow()
    
    if(self.current_row_new!=self.current_row):
        #ask for saving
        box = QMessageBox()
        box.setIcon(QMessageBox.Question)
        box.setWindowTitle('Αποθήκευση αλλαγών')
        box.setText('Θέλετε να αποθηκεύσετε τις αλλαγές σας;')
        box.setStandardButtons(QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel)
        buttonY = box.button(QMessageBox.Yes)
        buttonY.setText('Ναι')
        buttonN = box.button(QMessageBox.No)
        buttonN.setText('Οχι')
        buttonC = box.button(QMessageBox.Cancel)
        buttonC.setText('Ακύρωση')
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/menu_window_icons/media/images/save.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        box.setWindowIcon(icon)
        box.exec_()
        if box.clickedButton() == buttonY:
            self.save()
            self.current_row = self.current_row_new
            self.main_self.ui_edit_radio_stations_window.stations_list.setCurrentRow(self.current_row)
            self.show_radio_connection_details()
        elif box.clickedButton() == buttonN:
            self.current_row = self.current_row_new
            self.main_self.ui_edit_radio_stations_window.stations_list.setCurrentRow(self.current_row)
            self.show_radio_connection_details()
        elif box.clickedButton() == buttonC:
            self.previous_item_timer=QTimer()
            self.previous_item_timer.timeout.connect(self.return_to_previous_list_item)
            self.previous_item_timer.setSingleShot(True)
            self.previous_item_timer.start(100)
            
def return_to_previous_list_item(self):
    self.main_self.ui_edit_radio_stations_window.stations_list.setCurrentRow(self.current_row)
    self.current_row = self.main_self.ui_edit_radio_stations_window.stations_list.currentRow()

第一种方法被调用:使用这个命令:

self.main_self.ui_edit_radio_stations_window.stations_list.currentRowChanged.connect(lambda current_row:self.selected_radio_connection_changed(current_row))

其中stations_list 是一个QListWidget。

每次当前 qlist-item 改变时,就会打开一个 QMessageBox 提示。

使用前两个按钮,一切似乎都很好。但是当第三个被点击时,我想回滚到前一个 qlist-item。

问题是:为什么这个操作需要 QTimer?

我想在调用 selected_radio_connection_changed 方法之后有一个 event.accept() 。

标签: pythonpyqt5qlistwidget

解决方案


问题来自您试图当前索引更改中“覆盖”当前索引的事实。您应该对此更加小心,因为这样的交互可能会导致递归问题。

要始终考虑的重要一点是模型视图的当前索引并不总是与选择匹配。

设置当前索引应该在“当前更改”结束时发生,因此您可以安全地使用 QTimer使用视图的选择模型selectionChanged信号。

不幸的是,您没有提供足够清晰的MRE,因此很难为您提供更具体的解决方案,这取决于您的需求以及您如何实施整个过程。


推荐阅读