选择pyside listwidget项后,在python中添加它

时间:2015-10-30 12:07:22

标签: python list widget pyside

用户可以通过在文本输入中输入文本并点击键盘上的输入,将新的团队名称附加到列表中。

如何在添加到列表后选择项目?每次添加新项目时都要记住我希望列表首先按字母顺序重新排序。我知道如何按字母顺序排序,我只是不确定代码中的位置。

此代码段在下面的代码中用于按字母顺序排序......

# sort list by attribute name
        teamList.sort(key=lambda x: x._name, reverse=False)

代码包含一个Team类。这是代码......

enter image description here

 #!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Info goes here...
"""

import sys
from PySide import QtGui, QtCore

# Variables
# ------------------------------------------------------------------------------
teamList = []


# Classes
# ------------------------------------------------------------------------------
"""
Base class of team which contains 2 properties
name - name of team
members - list of team member names
"""
class Team:
    """
    One line description...
    other info....
    """
    def __init__(self, name, members=None):
        self._name = name
        if members==None:
            self._members = []

    @property
    def name(self, value):
        # add type validation lines here
        self._name = value

    @property
    def members(self, value):
        # add type validation lines here
        self._members = value


# Base widget widget
# ------------------------------------------------------------------------------
"""
Base widget which contains 
label - describes widget
textedit - input field for appending items to list
listview - displays the list of items teams or members
"""
class NameListWidget(QtGui.QWidget):

    def __init__(self, title=None):
        super(NameListWidget, self).__init__()

        self.initUI()
        if title!=None:
            self.listLabel.setText(title)

    def initUI(self): 

        # formatting 
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle("Input List")

        # widgets
        self.listLabel = QtGui.QLabel("Label")
        self.nameInput = QtGui.QLineEdit()
        self.nameList = QtGui.QListWidget()

        # signals
        self.nameInput.returnPressed.connect(self.pressed_return)

        # layout
        self.mainLayout = QtGui.QVBoxLayout(self)
        self.mainLayout.setContentsMargins(0,0,0,0)
        self.mainLayout.addWidget(self.listLabel)
        self.mainLayout.addWidget(self.nameInput)
        self.mainLayout.addWidget(self.nameList)
        self.show()

    def pressed_return(self):
        txt = self.nameInput.text()
        # remove leading and trailing whitespaces
        txt = txt.strip()
        # replace all remaining spaces with underscores
        txt = txt.replace (" ", "_")

        if (len(txt) >= 1):
            self.nameList.addItem(txt)
            self.nameInput.clear()


# Main widget
# ------------------------------------------------------------------------------
"""
Main team widget contains two instances of the nameList widget
left widget - contains a list of the team names
right widget - contains list of members names for the selected team
"""
class TeamsWidget(QtGui.QWidget):

    def __init__(self):
        super(TeamsWidget, self).__init__()

        self.initUI()

    def initUI(self): 

        # formatting 
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle("Teams")

        # widgets
        self.teamsListWidget = NameListWidget("Teams")

        # layout
        self.mainLayout = QtGui.QHBoxLayout(self)
        self.mainLayout.addWidget(self.teamsListWidget)
        self.show()

        self.populateUI()

    def populateUI(self):
        A = Team("Zebras")
        B = Team("Donuts")
        C = Team("Characters")
        D = Team("50")
        teamList.append(A)
        teamList.append(B)
        teamList.append(C)
        teamList.append(D)

        # sort list by attribute name
        teamList.sort(key=lambda x: x._name, reverse=False)

        self.teamsListWidget.nameList.clear()
        for t in teamList:
            self.teamsListWidget.nameList.addItem(t._name)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = TeamsWidget()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:2)

以下是您可以从上一个输入文字中选择项目的示例:

def pressed_return(self):
    txt = self.nameInput.text()
    # remove leading and trailing whitespaces
    txt = txt.strip()
    # replace all remaining spaces with underscores
    txt = txt.replace (" ", "_")

    if (len(txt) >= 1):
        self.nameList.addItem(txt)
        self.nameInput.clear()

    # EDITS HERE
    items = [self.nameList.item(i).text() for i in range( self.nameList.count() ) ] # Get text of all items
    if txt in items: # Check if text is in list
        index = items.index(txt) # Get text's index
        self.nameList.item(index).setSelected(True) # Select item

这个想法是它将获得每行的文本列表,获取新项目的行,然后选择它。如果您希望它的执行速度更快,您可以保存该项目的文字,因为您正在添加它们以跟踪它们。这样,每次添加新项目时都不需要从表中获取它。现在,如果您添加列表中已存在的文本,则此操作将失败,因此您可能需要对其进行条件检查。

您必须重新订购脚本,以便在向其添加新项目时重新排序项目(与现在populateUI相反)。