These are a bunch of convenience functions that I’ve been copying around from project to project for the last 7 years or so. They can be quite handy if you don’t want to subclass anything but still want a one liner to do certain tasks.


def add_items_to_combobox(combo_box, items, duplicates_allowed=False, clear=False, string_split_character=None):
    """
    Convenience function to add items to a combobox

    :param combo_box: your QComboBox
    :param items: a single string item, a list, or a string that can be split on a character like a comma separated string
    :param duplicates_allowed: whether or not allow duplicates in the combobox
    :param clear: clear the comboBox before adding stuff
    :param string_split_character: split the string on this character, the result is the list of items that get added to the combobox
    :return:
    """
    if not isinstance(items, (list, tuple)):
        if isinstance(items, str) and string_split_character is not None and string_split_character in items:
            tmpList = [part.strip() for part in items.split(string_split_character)]
            items = tmpList
        elif isinstance(items, str) and items == "":
            return
        else:
            items = [items]

    if clear is True:
        combo_box.clear()

    for item in items:
        if duplicates_allowed is True:
            combo_box.addItem(item)
        else:
            if combo_box.findText(item, QtCore.Qt.MatchExactly) == -1 and item is not None:
                combo_box.addItem(item)
def remove_items_from_combobox(combo_box, items, string_split_character=None):
    """
    Convenience function to remove items from a combo box

    :param combo_box: your QComboBox
    :param items: a single string item, a list, or a string that can be split on a character like a comma separated string
    :param string_split_character: split the string on this character, the result is the list of items that get added to the combobox
    :return:
    """
    if not isinstance(items, (list, tuple)):
        if isinstance(items, str) and string_split_character is not None and string_split_character in items:
            tmpList = [part.strip() for part in items.split(string_split_character)]
            items = tmpList
        else:
            items = [items]

    for item in items:
        index = combo_box.findText(item, QtCore.Qt.MatchExactly)
        if index != -1:
            combo_box.removeItem(index)

def set_combobox_to_item(combo_box, item_text, reload=False):
    """
    Convenience function to set the text of a combobox to a certain item of the combobox

    :param combo_box: your QComboBox
    :param item_text: text you're looking for
    :param reload: if True will reload the combobox, even if the text you're setting it to
    is the current text
    :return:
    """
    if reload is True:
        combo_box.setCurrentIndex(-1)

    index = combo_box.findText(item_text, QtCore.Qt.MatchExactly)
    if index != -1:
        combo_box.setCurrentIndex(index)
    else:
        raise ValueError("%s is not an item in %s" % (item_text, combo_box.objectName()))

def get_all_items_in_combobox(comboBox):
    """
    Gets all the items in a combobox as a list. Will raise an IndexError if there are not

    items in the combobox
    :param comboBox: your QComboBox
    :return: items of the QComboBox
    """
    items = []
    for item in [comboBox.itemText(i) for i in
                 xrange(comboBox.count())]:
        if item is not None:
            items.append(item)

    return items

def add_items_to_list_widget(list_widget, items, duplicates_allowed=False, string_split_character=None, clear=False):
    """
    Convenience function to add items to your list widget

    :param list_widget: your QListWidget
    :param items: a single string item, a list, or a string that can be split on a character like a comma separated string
    :param duplicates_allowed: bool, whether or not to allow duplicates
    :param string_split_character: if you pass a string into items, this character will be used to split the string into separate items
    :param clear: whether or not to clear the listWidget first
    :return:
    """
    if not isinstance(items, (list, tuple)):
        if isinstance(items, str) and string_split_character is not None and string_split_character in items:
            tmpList = [part.strip() for part in items.split(string_split_character)]
            items = tmpList
        elif isinstance(items, str) and items == "":
            return
        else:
            items = [items]

    if clear is True:
        list_widget.clear()

    for item in items:
        if duplicates_allowed is True:
            list_widget.addItem(item)
        else:
            if len(list_widget.findItems(item, QtCore.Qt.MatchExactly)) == 0 and item is not None:
                list_widget.addItem(item)

def remove_items_from_list_widget(listWidget, items=None, selected=False, stringSplitCharacter=None):
    """
    Convenience function to remove items from a listWidget

    :param listWidget: your QListWidget
    :param items: a single string item, a list, or a string that can be split on a character like a comma separated string
    :param stringSplitCharacter: if you pass a string into items, this character will be used to split the string into separate items
    :return:
    """
    if items is not None:
        if not isinstance(items, (list, tuple)):
            if isinstance(items, str) and stringSplitCharacter is not None and stringSplitCharacter in items:
                tmpList = [part.strip() for part in items.split(stringSplitCharacter)]
                items = tmpList
            else:
                items = [items]

    if selected:
        items = listWidget.selectedItems()

    for item in items:
        listWidget.takeItem(listWidget.row(item))

def get_all_items_in_list_widget(list_widget, as_string=True):
    """
    Gets all the items ina combobox as a list

    :param list_widget: your QListWidget
    :param as_string: if set to true, will return the text of the item. If set to false
    will return the actual QListWidgetItem
    :return: items of your QListWidget
    """
    items = []

    if as_string is True:
        for item in [list_widget.item(i).text() for i in
                     range(list_widget.count())]:
            if item is not None:
                items.append(item)
    else:
        for item in range(list_widget.count()):
            items.append(item)

    return items
def get_text_from_selected_tree_widget_items(tree_widget, column_index):
    text_list = []
    model_indexes = tree_widget.selectedIndexes()
    for model_index in model_indexes:
        item = tree_widget.itemFromIndex(model_index)

        text_list.append(item.text(column_index))

    return text_list
def get_item_with_text_from_tree_widget(tree_widget, text, column_index):
    """
    Returns a QTreeWidgetItem that matches the selected text for the selected column

    :param tree_widget: QTreeWidget you want to search in
    :param text: string text
    :param column_index: int column number
    :return: QTreeWidgetItem if found or None if not found
    """
    try:
        iterator = QtWidgets.QTreeWidgetItemIterator(tree_widget)
        while iterator:
            if iterator.value().text(column_index) == text:
                return iterator.value()
            iterator +=1
    except:
        return None

    return None
def remove_items_from_tree_widget(tree_widget, items=[], selected=False):
    """
    Removes the passed items from the tree widget

    :param tree_widget: QTreeWidget to remove items from
    :param items: items you want to remove
    :param selected: <bool> if set to True, will remove the selected items
    :return:
    """
    if selected == True:
        items = tree_widget.selectedItems()

    root = tree_widget.invisibleRootItem()
    for item in items:
        (item.parent() or root).removeChild(item)
def clear_layout(layout):
    for i in reversed(range(layout.count())):
        layout.itemAt(i).widget().setParent(None)