سؤال

I have an application written in Python using PySide, the UI was created with QT Designer.

I have a list in the window, which has a set of items. When the application loads, it seems to grab the last item in the list (even though there is no 'highlighted' row showing in the list). If I break and check if there is a selected item at that time, I will get the last item in the list.

I have this code:

    @QtCore.Slot(QTreeWidgetItem,QTreeWidgetItem)
    def on_list_currentItemChanged(self,current=None,previous=None):
        if current:
            self.ui.actionDelete_Task.setEnabled(True)
        else:
            self.ui.actionDelete_Task.setEnabled(False)

Which determines if there is a current item selected. So upon initial load, I expect current to be empty, but it's not, it's pointing to the last item in the list, even though no item has been selected.

Is there something that I'm missing? Or, alternatively, how do I tell the list to not have a selected row/deselect all rows?

Ultimately what I'm looking for is (a) that when the form loads and the list is originally shown with no selected item, that the delete button is disabled and even (b) if someone should delete an item through this action, there won't be a selected item after that (so they couldn't just hit delete twice and delete two rows in sequence).

هل كانت مفيدة؟

المحلول

The current item and the selection are not necessarily the same thing. The current item refers to the item with the keyboard focus; the selection refers to the currently highlighted items. So a tree widget with no selection will still have a current item (unless it has no items at all).

So one solution might be to simply check that the current item is also selected:

@QtCore.Slot(QTreeWidgetItem, QTreeWidgetItem)
def on_list_currentItemChanged(self, current=None, previous=None):
    if current is not None and current.isSelected():
        self.ui.actionDelete_Task.setEnabled(True)
    else:
        self.ui.actionDelete_Task.setEnabled(False)

EDIT

After taking a look at the Qt source code, it appears the above code won't work because the currentItemChanged signal is emitted before the selection is reset.

So, instead, I would suggest using the itemSelectionChanged signal, and checking the selectedItems:

def on_list_ItemSelectionChanged(self):
    if self.list.selectedItems():
        self.ui.actionDelete_Task.setEnabled(True)
    else:
        self.ui.actionDelete_Task.setEnabled(False)

NB: taking this approach may also entail replacing the usage of currentItem() with selectedItems()[0] elsewhere in your code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top