TTkListWidget🌶️

class TTkListWidget(*, items: List[TTkAbstractListItem | Any] = [], selectionMode: SelectionMode = SelectionMode.SingleSelection, dragDropMode: DragDropMode = DragDropMode.NoDragDrop, showSearch: bool = True, **kwargs)[source]🌶️

Bases: TTkAbstractScrollView

TTkListWidget:

A widget that displays a scrollable list of selectable items with optional search functionality.

This widget supports single/multiple selection modes, drag-and-drop reordering, keyboard navigation, and incremental search. Items can be strings or custom TTkAbstractListItem widgets.

╔════════════════════════════════╗
║Search: te_                    ▲║ ← Search bar (optional)
║S-0) --Zero-3- officia         ▓║
║S-1) ad ipsum                  ┊║
║S-2) irure nisi                ┊║ ← Scrollable items
║S-3) minim --Zero-3-           ┊║
║S-4) ea sunt                   ┊║
║S-5) qui mollit                ┊║
║S-6) magna sunt                ┊║
║S-7) sunt officia              ▼║
╚════════════════════════════════╝

Demo: list.py (online)

import TermTk as ttk

root = ttk.TTk(layout=ttk.TTkGridLayout(), mouseTrack=True)

# Simple string list
l1 = ttk.TTkList(parent=root, items=[123, 456, 789])
id1 = l1.indexOf(456)
l1.setCurrentRow(id1)

# List with many items (scrollable)
ttk.TTkList(parent=root, items=[f"Item 0x{i:03X}" for i in range(100)])

# Multi-selection list with drag-drop
ttkList = ttk.TTkList(
    parent=root,
    selectionMode=ttk.TTkK.SelectionMode.MultiSelection,
    dragDropMode=ttk.TTkK.DragDropMode.AllowDragDrop
)
ttkList.addItems([f"Item 0x{i:04X}" for i in range(50)])

root.layout().addWidget(ttk.TTkLogViewer(),1,0,1,3)

# Handle selection
@ttk.pyTTkSlot(str)
def on_item_clicked(text):
    ttk.TTkLog.debug(f"Clicked: {text}")

ttkList.textClicked.connect(on_item_clicked)

root.mainloop()

Features:

  • Single or multiple selection modes

  • Keyboard navigation (arrows, page up/down, home/end)

  • Incremental search by typing

  • Drag-and-drop reordering (optional)

  • Custom item widgets via TTkAbstractListItem

  • Signals for item selection and search events

Parameters:

TTkContainer’s inherited init params:

Parameters:
  • layout (TermTk.TTkLayouts) – the layout of this widget, optional, defaults to TTkLayout

  • padding (TTkPadding) – the padding (top, bottom, left, right) of the widget, defaults to (0,0,0,0)

  • paddingTop (int) – the Top padding, override Top padding if already defined, optional, default=0 if padding is not defined

  • paddingBottom (int) – the Bottom padding, override Bottom padding if already defined, optional, default=0 if padding is not defined

  • paddingLeft (int) – the Left padding, override Left padding if already defined, optional, default=0 if padding is not defined

  • paddingRight (int) – the Right padding, override Right padding if already defined, optional, default=0 if padding is not defined

  • forwardStyle (bool) – [Experimental] any change of style will reflect the children, defaults to False

TTkWidget’s inherited init params:

Parameters:
  • name (str, optional) – the name of the widget, defaults to “”

  • parent (TTkWidget, optional) – the parent widget, defaults to None

  • x (int, optional) – the x position, defaults to 0

  • y (int, optional) – the y position, defaults to 0

  • pos ((int,int), optional) – the [x,y] position (override the previously defined x, y), defaults to (x,y)

  • width (int, optional) – the width of the widget, defaults to 0

  • height (int, optional) – the height of the widget, defaults to 0

  • size ((int,int), optional) – the size [width, height] of the widget (override the previously defined sizes), defaults to (width,height)

  • maxWidth (int, optional) – the maxWidth of the widget, defaults to 0x10000

  • maxHeight (int, optional) – the maxHeight of the widget, defaults to 0x10000

  • maxSize ((int,int), optional) – the max [width,height] of the widget, optional, defaults to (maxWidth,maxHeight)

  • minWidth (int, optional) – the minWidth of the widget, defaults to 0

  • minHeight (int, optional) – the minHeight of the widget, defaults to 0

  • minSize ((int,int), optional) – the minSize [width,height] of the widget, optional, defaults to (minWidth,minHeight)

  • toolTip (TTkString, optional) – This property holds the widget’s tooltip, defaults to ‘’

  • style (dict, optional) – this field hold the custom style to be used by this widget

  • addStyle (dict, optional) – this field is required to override/merge the new style on top of the current one, useful if only few params need to be changed

  • visible (bool, optional) – the visibility, optional, defaults to True

  • enabled (bool, optional) – the ability to handle input events, optional, defaults to True

TMouseEvents’s inherited init params:

Initialize self. See help(type(self)) for accurate signature.

TDragEvents’s inherited init params:

Initialize self. See help(type(self)) for accurate signature.

Style🌶️

classStyle = {
    'default':{'searchColor': TTkColor.fg("#FFFF00") + TTkColor.UNDERLINE}}

@dataclass(frozen=True)
class _DropListData:
    widget: TTkAbstractScrollView
    items: list

__slots__ = ('_selectedItems', '_selectionMode',
             '_highlighted', '_items', '_filteredItems',
             '_dragPos', '_dndMode',
             '_searchText', '_showSearch',
             # Signals
             '_itemClicked', '_textClicked', '_searchModified')

_items:List[TTkAbstractListItem]
_showSearch:bool
_highlighted:Optional[TTkAbstractListItem]
_selectedItems:List[TTkAbstractListItem]
_filteredItems:List[TTkAbstractListItem]

def __init__(self, *,
             items:List[TTkAbstractListItemType]=[],
             selectionMode:TTkK.SelectionMode=TTkK.SelectionMode.SingleSelection,
             dragDropMode:TTkK.DragDropMode=TTkK.DragDropMode.NoDragDrop,
             showSearch:bool=True,
             **kwargs) -> None:
    '''
    :param items: Initial list of items (Any or :py:class:`TTkAbstractListItem` objects), defaults to []
    :type items: list, optional
    :param selectionMode: Selection behavior (:py:class:`TTkK.SelectionMode.SingleSelection` or :py:class:`TTkK.SelectionMode.MultiSelection`), defaults to :py:class:`TTkK.SelectionMode.SingleSelection`
    :type selectionMode: :py:class:`TTkK.SelectionMode`, optional
    :param dragDropMode: Drag and drop behavior (NoDragDrop, InternalMove, DragOnly, DropOnly, DragDrop), defaults to NoDragDrop
    :type dragDropMode: :py:class:`TTkK.DragDropMode`, optional
    :param showSearch: Whether to show the search hint at the top, defaults to True
    :type showSearch: bool, optional
    '''
    # Signals
    self._itemClicked = pyTTkSignal(TTkAbstractListItem)
    self._textClicked = pyTTkSignal(str)
    self._searchModified = pyTTkSignal(str)

    # Default Class Specific Values
    self._selectionMode = selectionMode
    self._selectedItems = []
    self._items = []
    self._filteredItems = self._items
    self._highlighted = None
    self._dragPos = None
    self._dndMode = dragDropMode
    self._searchText:str = ''
    self._showSearch:bool = showSearch
    # Init Super
    super().__init__(**kwargs)
    self.addItemsAt(items=items, pos=0)
    self.viewChanged.connect(self._viewChangedHandler)
    self.setFocusPolicy(TTkK.ClickFocus | TTkK.TabFocus)
    self.searchModified.connect(self._searchModifiedHandler)

@pyTTkSlot()
def _viewChangedHandler(self):
    x,y = self.getViewOffsets()
    self.layout().setOffset(-x,-y)

@pyTTkSlot(TTkAbstractListItem)
def _labelSelectedHandler(self, label:TTkAbstractListItem):
    if self._selectionMode == TTkK.SingleSelection:
        for item in self._selectedItems:
            item._setSelected(False)
            item._setHighlighted(False)
        self._selectedItems = [label]
        label._setSelected(True)
    elif self._selectionMode == TTkK.MultiSelection:
        for item in self._selectedItems:
            item._setHighlighted(False)
        label._setSelected(not label._selected)
        if label._selected:
            self._selectedItems.append(label)
        else:
            self._selectedItems.remove(label)
    if self._highlighted:
        self._highlighted._setHighlighted(False)
    label._setHighlighted(True)
    self._highlighted = label
    self.itemClicked.emit(label)
    self.textClicked.emit(label.text())

@pyTTkSlot(str)
def _searchModifiedHandler(self) -> None:
    if self._showSearch and self._searchText:
        self.setPadding(1,0,0,0)
    else:
        self.setPadding(0,0,0,0)

    if self._searchText:
        text = self._searchText.lower()
        self._filteredItems = [i for i in self._items if text in i._lowerText]
        for item in self._items:
            item._quickVisible = text in item._lowerText
    else:
        self._filteredItems = self._items
        for item in self._items:
            item._quickVisible = True
            item.setVisible(True)

    self._placeItems()

def search(self) -> str:
    '''
    Returns the current search text.

    :return: The active search filter string
    :rtype: str
    '''
    return self._searchText

def setSearch(self, search:str) -> None:
    '''
    Sets the search text to filter items.

    :param search: The search string to filter by
    :type search: str
    '''
    self._searchText = search
    self.searchModified.emit(search)

def searchVisibility(self) -> bool:
    '''
    Returns whether the search hint is visible.

    :return: True if search hint is shown
    :rtype: bool
    '''
    return self._showSearch

def setSearchVisibility(self, visibility:bool) -> None:
    '''
    Sets the visibility of the search hint at the top of the list.

    :param visibility: True to show search hint, False to hide
    :type visibility: bool
    '''
    self._showSearch = visibility

def dragDropMode(self) -> TTkK.DragDropMode:
    '''
    Returns the current drag-drop mode.

    :return: The drag-drop behavior setting
    :rtype: :py:class:`TTkK.DragDropMode`
    '''
    return self._dndMode

def setDragDropMode(self, dndMode:TTkK.DragDropMode) -> None:
    '''
    Sets the drag-drop mode for this list.

    :param dndMode: The new drag-drop behavior
    :type dndMode: :py:class:`TTkK.DragDropMode`
    '''
    self._dndMode = dndMode

def selectionMode(self) -> TTkK.SelectionMode:
    '''
    Returns the current selection mode.

    :return: The selection behavior setting
    :rtype: :py:class:`TTkK.SelectionMode`
    '''
    return self._selectionMode

def setSelectionMode(self, mode:TTkK.SelectionMode) -> None:
    '''
    Sets the selection mode for this list.

    :param mode: The new selection behavior (SingleSelection or MultiSelection)
    :type mode: :py:class:`TTkK.SelectionMode`
    '''
    self._selectionMode = mode

def selectedItems(self) -> List[TTkAbstractListItem]:
    '''
    Returns the list of currently selected items.

    :return: List of selected item widgets
    :rtype: list[:py:class:`TTkAbstractListItem`]
    '''
    return self._selectedItems

def selectedLabels(self) -> List[str]:
    '''
    Returns the text of all selected items.

    :return: List of selected item texts
    :rtype: list[str]
    '''
    return [i.text() for i in self._selectedItems]

def items(self) -> List[TTkAbstractListItem]:
    '''
    Returns all items in the list.

    :return: Complete list of items
    :rtype: list[:py:class:`TTkAbstractListItem`]
    '''
    return self._items

def filteredItems(self) -> List[TTkAbstractListItem]:
    '''
    Returns items matching the current search filter.

    :return: Filtered list of visible items
    :rtype: list[:py:class:`TTkAbstractListItem`]
    '''
    return self._filteredItems

def resizeEvent(self, w:int, h:int) -> None:
    maxw = 0
    for item in self.layout().children():
        maxw = max(maxw,item.minimumWidth())
    maxw = max(self.width(),maxw)
    for item in self.layout().children():
        x,y,_,h = item.geometry()
        item.setGeometry(x,y,maxw,h)
    TTkAbstractScrollView.resizeEvent(self, w, h)

def addItem(self, item:TTkAbstractListItemType, data:Any=None) -> None:
    '''
    Appends a single item to the end of the list.

    :param item: The item to add (string or :py:class:`TTkAbstractListItem`)
    :type item: str or :py:class:`TTkAbstractListItem`
    :param data: Optional user data to associate with the item
    :type data: Any, optional
    '''
    self.addItemAt(item, len(self._items), data)

def addItems(self, items:List[TTkAbstractListItemType]) -> None:
    '''
    Appends multiple items to the end of the list.

    :param items: List of items to add (strings or :py:class:`TTkAbstractListItem` objects)
    :type items: list
    '''
    self.addItemsAt(items=items, pos=len(self._items))

def _placeItems(self) -> None:
    '''
    Internal method to position items in the layout.
    '''
    minw = self.width()
    for item in self._items:
        if item in self._filteredItems:
            minw = max(minw,item.minimumWidth())
    for y,item in enumerate(self._filteredItems):
        item.setGeometry(0,y,minw,1)
    self.viewChanged.emit()
    self.update()

def addItemAt(self, item:TTkAbstractListItemType, pos:int, data:Any=None) -> None:
    '''
    Inserts a single item at the specified position.

    :param item: The item to insert (string or :py:class:`TTkAbstractListItem`)
    :type item: str or :py:class:`TTkAbstractListItem`
    :param pos: The index position to insert at
    :type pos: int
    :param data: Optional user data to associate with the item
    :type data: Any, optional
    '''
    if isinstance(item, str) or isinstance(item, TTkString):
        item = TTkAbstractListItem(text=item, data=data)
    self.addItemsAt([item],pos)

def addItemsAt(self, items:List[TTkAbstractListItemType], pos:int) -> None:
    '''
    Inserts multiple items at the specified position.

    :param items: List of items to insert (strings or :py:class:`TTkAbstractListItem` objects)
    :type items: list
    :param pos: The index position to insert at
    :type pos: int
    '''
    items = [
        _i if isinstance(_i, TTkAbstractListItem)
        else TTkAbstractListItem(
                text=TTkString(_i if isinstance(_i,TTkString) else str(_i)),
                data=_i)
        for _i in items
    ]
    for item in items:
        if not issubclass(type(item),TTkAbstractListItem):
            TTkLog.error(f"{item=} is not an TTkAbstractListItem")
            return
    for item in items:
        item.listItemClicked.connect(self._labelSelectedHandler)
    self._items[pos:pos] = items
    self.layout().addWidgets(items)
    self._placeItems()

def indexOf(self, item:TTkAbstractListItemType) -> int:
    '''
    Returns the index of the given item.

    :param item: The item to find
    :type item: :py:class:`TTkAbstractListItem` or the data or the text to be searched
    :return: The index of the item, or -1 if not found
    :rtype: int
    '''
    if isinstance(item, TTkAbstractListItem):
        return self._items.index(item)
    for i, it in enumerate(self._items):
        if it.data() == item or it.text() == item:
            return i
    return -1

def itemAt(self, pos:int) -> TTkAbstractListItem:
    '''
    Returns the item at the specified index.

    :param pos: The index position
    :type pos: int
    :return: The item at that position
    :rtype: :py:class:`TTkAbstractListItem`
    '''
    return self._items[pos]

def moveItem(self, fr:int, to:int) -> None:
    '''
    Moves an item from one position to another.

    :param fr: The source index
    :type fr: int
    :param to: The destination index
    :type to: int
    '''
    fr = max(min(fr,len(self._items)-1),0)
    to = max(min(to,len(self._items)-1),0)
    # Swap
    self._items[to] , self._items[fr] = self._items[fr] , self._items[to]
    self._placeItems()

def removeItem(self, item:TTkAbstractListItem) -> None:
    '''
    Removes a single item from the list.

    :param item: The item to remove
    :type item: :py:class:`TTkAbstractListItem`
    '''
    self.removeItems([item])

def removeItems(self, items:List[TTkAbstractListItem]) -> None:
    '''
    Removes multiple items from the list.

    :param items: List of items to remove
    :type items: list[:py:class:`TTkAbstractListItem`]
    '''
    self.layout().removeWidgets(items)
    for item in items.copy():
        item.listItemClicked.disconnect(self._labelSelectedHandler)
        item._setSelected(False)
        item._setHighlighted(False)
        self._items.remove(item)
        if item in self._selectedItems:
            self._selectedItems.remove(item)
        if item == self._highlighted:
            self._highlighted = None
    self._placeItems()

def removeAt(self, pos:int) -> None:
    '''
    Removes the item at the specified index.

    :param pos: The index of the item to remove
    :type pos: int
    '''
    self.removeItem(self._items[pos])

def setCurrentRow(self, row:int) -> None:
    '''
    Selects the item at the specified row.

    :param row: The row index to select
    :type row: int
    '''
    if row<len(self._items):
        item = self._items[row]
        self.setCurrentItem(item)

def setCurrentItem(self, item:TTkAbstractListItem) -> None:
    '''
    Selects the specified item and emits the itemClicked signal.

    :param item: The item to select
    :type item: :py:class:`TTkAbstractListItem`
    '''
    item.listItemClicked.emit(item)

def _moveToHighlighted(self) -> None:
    '''
    Internal method to scroll the view to show the highlighted item.
    '''
    index = self._items.index(self._highlighted)
    h = self.height()
    offx,offy = self.getViewOffsets()
    if index >= h+offy-1:
        self.viewMoveTo(offx, index-h+1)
    elif index <= offy:
        self.viewMoveTo(offx, index)

def mousePressEvent(self, evt:TTkMouseEvent) -> bool:
    return True

def mouseDragEvent(self, evt:TTkMouseEvent) -> bool:
    if not(self._dndMode & TTkK.DragDropMode.AllowDrag):
        return False
    if not (items:=self._selectedItems.copy()):
        return True
    drag = TTkDrag()
    data =TTkListWidget._DropListData(widget=self,items=items)
    h = min(3,ih:=len(items)) + 2 + (1 if ih>3 else 0)
    w = min(20,iw:=max([it.text().termWidth() for it in items[:3]])) + 2
    pm = TTkCanvas(width=w,height=h)
    for y,it in enumerate(items[:3],1):
        txt = it.text()
        if txt.termWidth() < 20:
            pm.drawText(pos=(1,y), text=it.text())
        else:
            pm.drawText(pos=(1,y), text=it.text(), width=17)
            pm.drawText(pos=(18,y), text='...')
    if ih>3:
        pm.drawText(pos=(1,4), text='...')
    pm.drawBox(pos=(0,0),size=(w,h))
    drag.setPixmap(pm)
    drag.setData(data)
    drag.exec()
    return True

def dragEnterEvent(self, evt:TTkDnDEvent) -> bool:
    if not(self._dndMode & TTkK.DragDropMode.AllowDrop):
        return False
    if issubclass(type(evt.data()),TTkListWidget._DropListData):
        return self.dragMoveEvent(evt)
    return False

def dragMoveEvent(self, evt:TTkDnDEvent) -> bool:
    offx,offy = self.getViewOffsets()
    y=min(evt.y+offy,len(self._items))
    self._dragPos = (offx+evt.x, y)
    self.update()
    return True

def dragLeaveEvent(self, evt:TTkDnDEvent) -> bool:
    self._dragPos = None
    self.update()
    return True

def dropEvent(self, evt:TTkDnDEvent) -> bool:
    if not(self._dndMode & TTkK.DragDropMode.AllowDrop):
        return False
    self._dragPos = None
    if not issubclass(type(evt.data())  ,TTkListWidget._DropListData):
        return False
    t,b,l,r = self.getPadding()
    offx,offy = self.getViewOffsets()
    wid   = evt.data().widget
    items = evt.data().items
    if wid and items:
        wid.removeItems(items)
        wid._searchModifiedHandler()
        for it in items:
            it.setCurrentStyle(it.style()['default'])
        yPos = offy+evt.y-t
        if self._filteredItems:
            if yPos < 0:
                yPos = 0
            elif yPos > len(self._filteredItems):
                yPos = len(self._items)
            elif yPos == len(self._filteredItems):
                filteredItemAt = self._filteredItems[-1]
                yPos = self._items.index(filteredItemAt)+1
            else:
                filteredItemAt = self._filteredItems[yPos]
                yPos = self._items.index(filteredItemAt)
        else:
            yPos = 0
        self.addItemsAt(items,yPos)
        self._searchModifiedHandler()
        return True
    return False

def keyEvent(self, evt:TTkKeyEvent) -> bool:
    # if not self._highlighted: return False
    if ( not self._searchText and evt.type == TTkK.Character and evt.key==" " ) or \
       ( evt.type == TTkK.SpecialKey and evt.key == TTkK.Key_Enter ):
        if self._highlighted:
            self._highlighted.listItemClicked.emit(self._highlighted)

    elif evt.type == TTkK.Character:
        # Add this char to the search text
        self._searchText += evt.key
        self.update()
        self.searchModified.emit(self._searchText)

    elif ( evt.type == TTkK.SpecialKey and
           evt.key == TTkK.Key_Tab ):
        return False

    elif ( evt.type == TTkK.SpecialKey and
           evt.key in (TTkK.Key_Delete,TTkK.Key_Backspace) and
           self._searchText ):
        # Handle the backspace to remove the last char from the search text
        self._searchText = self._searchText[:-1]
        self.update()
        self.searchModified.emit(self._searchText)

    elif ( evt.type == TTkK.SpecialKey and
           self._filteredItems):
        # Handle the arrow/movement keys
        index = 0
        if self._highlighted:
            self._highlighted._setHighlighted(False)
            if self._highlighted not in self._filteredItems:
                self._highlighted = self._filteredItems[0]
            index = self._filteredItems.index(self._highlighted)
        offx,offy = self.getViewOffsets()
        h = self.height()
        if evt.key == TTkK.Key_Up:
            index = max(0, index-1)
        elif evt.key == TTkK.Key_Down:
            index = min(len(self._filteredItems)-1, index+1)
        elif evt.key == TTkK.Key_PageUp:
            index = max(0, index-h)
        elif evt.key == TTkK.Key_PageDown:
            index = min(len(self._filteredItems)-1, index+h)
        elif evt.key == TTkK.Key_Right:
            self.viewMoveTo(offx+1, offy)
        elif evt.key == TTkK.Key_Left:
            self.viewMoveTo(offx-1, offy)
        elif evt.key == TTkK.Key_Home:
            self.viewMoveTo(0, offy)
        elif evt.key == TTkK.Key_End:
            self.viewMoveTo(0x10000, offy)
        elif evt.key in (TTkK.Key_Delete,TTkK.Key_Backspace):
            if self._searchText:
                self._searchText = self._searchText[:-1]
                self.update()
                self.searchModified.emit(self._searchText)
        self._highlighted = self._filteredItems[index]
        self._highlighted._setHighlighted(True)
        self._moveToHighlighted()

    else:
        return False
    return True

def focusInEvent(self):
    if not self._items: return
    if not self._highlighted:
        self._highlighted = self._items[0]
    self._highlighted._setHighlighted(True)

def focusOutEvent(self):
    if self._highlighted:
        self._highlighted._setHighlighted(False)
    self._dragPos = None

# Stupid hack to paint on top of the child widgets
def paintChildCanvas(self):
    super().paintChildCanvas()
    if self._dragPos:
        canvas = self.getCanvas()
        x,y = self._dragPos
        offx,offy = self.getViewOffsets()
        p1 = (0,y-offy-1)
        p2 = (0,y-offy)
        canvas.drawText(pos=p1,text="╙─╼", color=TTkColor.fg("#FFFF00")+TTkColor.bg("#008855"))
        canvas.drawText(pos=p2,text="╓─╼", color=TTkColor.fg("#FFFF00")+TTkColor.bg("#008855"))

def paintEvent(self, canvas: TTkCanvas) -> None:
    if self._showSearch and self._searchText:
        w,h = self.size()
        color = self.currentStyle()['searchColor']
        if len(self._searchText) > w:
            text = TTkString("≼",TTkColor.BG_BLUE+TTkColor.FG_CYAN)+TTkString(self._searchText[-w+1:],color)
        else:
            text = TTkString(self._searchText,color)
        canvas.drawTTkString(pos=(0,0),text=text, color=color, width=w)

Signals🌶️

closed

This signal is emitted whenever the widget is closed

currentStyleChanged

This signal is emitted whenever the widget stye change

focusChanged

This signal is emitted whenever the focus status change i.e. with the setFocus() or clearFocus() methods.

sizeChanged

This signal is emitted whenever the widget size change

viewChanged

This signal is emitted whenever there is a change in the view content topology (size,pos)

viewMovedTo

This signal is emitted when the view content move to a new position (x,y),

viewSizeChanged

This signal is emitted when the view content size changed

Slots🌶️

Slots Inherited from: TTkAbstractScrollView

viewMoveTo(x, y)

Move the view to the specified offset position

Slots Inherited from: TTkContainer

hide()

hide the widget

show()

show the widget

Slots Inherited from: TTkWidget

close()

Close (Destroy/Remove) the widget

hide()

hide the widget

lowerWidget()

Lower the Widget below its relatives

raiseWidget([raiseParent])

Raise the Widget above its relatives

setDisabled([disabled])

This property holds whether the widget is disnabled

setEnabled([enabled])

This property holds whether the widget is enabled

setFocus()

Focus the widget

setVisible(visible)

Set the visibility status of this widget

show()

show the widget

update([repaint, updateLayout, updateParent])

Update the widget and emit viewChanged signal if layout is updated

Members🌶️

closed: pyTTkSignal🌶️

This signal is emitted whenever the widget is closed

Parameters:

widget (TTkWidget) – the widget closed (=self)

currentStyleChanged: pyTTkSignal🌶️

This signal is emitted whenever the widget stye change

Parameters:

style (dict) – the new style applied

focusChanged: pyTTkSignal🌶️

This signal is emitted whenever the focus status change i.e. with the setFocus() or clearFocus() methods

Parameters:

status (bool) – the curent focus status

sizeChanged: pyTTkSignal🌶️

This signal is emitted whenever the widget size change

Parameters:
  • width (int) – the new widget width

  • height (int) – the new widget height

viewChanged: pyTTkSignal🌶️

This signal is emitted whenever there is a change in the view content topology (size,pos)

Note

This signal must be implemented in any implementation of TTkAbstractScrollView to notify that the view content boudaries changed

viewMovedTo: pyTTkSignal🌶️

This signal is emitted when the view content move to a new position (x,y),

Parameters:
  • x (int) – the new horizontal offset

  • y (int) – the new vertical offset

viewSizeChanged: pyTTkSignal🌶️

This signal is emitted when the view content size changed

Parameters:
  • width (int) – the new width

  • height (int) – the new height

Methods🌶️

addItem(item: TTkAbstractListItem | Any, data: Any = None) None[source]🌶️

Appends a single item to the end of the list.

Parameters:
addItemAt(item: TTkAbstractListItem | Any, pos: int, data: Any = None) None[source]🌶️

Inserts a single item at the specified position.

Parameters:
  • item (str or TTkAbstractListItem) – The item to insert (string or TTkAbstractListItem)

  • pos (int) – The index position to insert at

  • data (Any, optional) – Optional user data to associate with the item

addItems(items: List[TTkAbstractListItem | Any]) None[source]🌶️

Appends multiple items to the end of the list.

Parameters:

items (list) – List of items to add (strings or TTkAbstractListItem objects)

addItemsAt(items: List[TTkAbstractListItem | Any], pos: int) None[source]🌶️

Inserts multiple items at the specified position.

Parameters:
  • items (list) – List of items to insert (strings or TTkAbstractListItem objects)

  • pos (int) – The index position to insert at

dragDropMode() DragDropMode[source]🌶️

Returns the current drag-drop mode.

Returns:

The drag-drop behavior setting

Return type:

TTkK.DragDropMode

filteredItems() List[TTkAbstractListItem][source]🌶️

Returns items matching the current search filter.

Returns:

Filtered list of visible items

Return type:

list[TTkAbstractListItem]

indexOf(item: TTkAbstractListItem | Any) int[source]🌶️

Returns the index of the given item.

Parameters:

item (TTkAbstractListItem or the data or the text to be searched) – The item to find

Returns:

The index of the item, or -1 if not found

Return type:

int

itemAt(pos: int) TTkAbstractListItem[source]🌶️

Returns the item at the specified index.

Parameters:

pos (int) – The index position

Returns:

The item at that position

Return type:

TTkAbstractListItem

items() List[TTkAbstractListItem][source]🌶️

Returns all items in the list.

Returns:

Complete list of items

Return type:

list[TTkAbstractListItem]

moveItem(fr: int, to: int) None[source]🌶️

Moves an item from one position to another.

Parameters:
  • fr (int) – The source index

  • to (int) – The destination index

removeAt(pos: int) None[source]🌶️

Removes the item at the specified index.

Parameters:

pos (int) – The index of the item to remove

removeItem(item: TTkAbstractListItem) None[source]🌶️

Removes a single item from the list.

Parameters:

item (TTkAbstractListItem) – The item to remove

removeItems(items: List[TTkAbstractListItem]) None[source]🌶️

Removes multiple items from the list.

Parameters:

items (list[TTkAbstractListItem]) – List of items to remove

search() str[source]🌶️

Returns the current search text.

Returns:

The active search filter string

Return type:

str

searchVisibility() bool[source]🌶️

Returns whether the search hint is visible.

Returns:

True if search hint is shown

Return type:

bool

selectedItems() List[TTkAbstractListItem][source]🌶️

Returns the list of currently selected items.

Returns:

List of selected item widgets

Return type:

list[TTkAbstractListItem]

selectedLabels() List[str][source]🌶️

Returns the text of all selected items.

Returns:

List of selected item texts

Return type:

list[str]

selectionMode() SelectionMode[source]🌶️

Returns the current selection mode.

Returns:

The selection behavior setting

Return type:

TTkK.SelectionMode

setCurrentItem(item: TTkAbstractListItem) None[source]🌶️

Selects the specified item and emits the itemClicked signal.

Parameters:

item (TTkAbstractListItem) – The item to select

setCurrentRow(row: int) None[source]🌶️

Selects the item at the specified row.

Parameters:

row (int) – The row index to select

setDragDropMode(dndMode: DragDropMode) None[source]🌶️

Sets the drag-drop mode for this list.

Parameters:

dndMode (TTkK.DragDropMode) – The new drag-drop behavior

setSearch(search: str) None[source]🌶️

Sets the search text to filter items.

Parameters:

search (str) – The search string to filter by

setSearchVisibility(visibility: bool) None[source]🌶️

Sets the visibility of the search hint at the top of the list.

Parameters:

visibility (bool) – True to show search hint, False to hide

setSelectionMode(mode: SelectionMode) None[source]🌶️

Sets the selection mode for this list.

Parameters:

mode (TTkK.SelectionMode) – The new selection behavior (SingleSelection or MultiSelection)

Methods Inherited from: TTkAbstractScrollView

getViewOffsets()

Retrieve the vertical and horizontal offsets of the TTkAbstractScrollViewInterface

resizeEvent(w, h)

Handle resize events

setPadding(top, bottom, left, right)

Set the padding and emit viewChanged signal

update([repaint, updateLayout, updateParent])

Update the widget and emit viewChanged signal if layout is updated

viewDisplayedSize()

Return the displayed size of this view

viewFullAreaSize()

Return the full area size including padding

viewMoveTo(x, y)

Move the view to the specified offset position

wheelEvent(evt)

Handle mouse wheel events for scrolling

Methods Inherited from: TTkContainer

addWidget(widget)

getPadding()

Retrieve the TTkContainer's paddings sizes as shown in Layout Topology

getWidgetByName(name)

Return the widget from its name.

hide()

hide the widget

keyEvent(evt)

This event handler, can be reimplemented in a subclass to receive key events for the widget.

layout()

Get the Layout

maximumHeight()

maximumWidth()

minimumHeight()

minimumWidth()

paintChildCanvas()

removeWidget(widget)

rootLayout()

This is a root layout mainly used to place items that are not supposed to be inside the main layout (i.e. the menu elements).

setCurrentStyle(*args, **kwargs)

setLayout(layout)

Set the Layout used by this widget to place all the child widgets.

setPadding(top, bottom, left, right)

Set the padding and emit viewChanged signal

show()

show the widget

update([repaint, updateLayout, updateParent])

Update the widget and emit viewChanged signal if layout is updated

Methods Inherited from: TTkWidget

clearFocus()

Remove the Focus state of this widget

close()

Close (Destroy/Remove) the widget

currentStyle()

disableWidgetCursor([disable])

enableWidgetCursor([enable])

focusInEvent()

focusOutEvent()

focusPolicy()

geometry()

getCanvas()

getPixmap()

Convenience function which return a pixmap representing the current widget status

getWidgetByName(name)

Return the widget from its name.

hasFocus()

This property holds the focus status of this widget

height()

hide()

hide the widget

isEnabled()

This property holds whether the widget is enabled

isEntered()

isVisible()

Retrieve the visibility status of this widget

isVisibleAndParent()

lowerWidget()

Lower the Widget below its relatives

maxDimension(orientation)

maximumHeight()

maximumSize()

maximumWidth()

mergeStyle(style)

minDimension(orientation)

minimumHeight()

minimumSize()

minimumWidth()

mouseEvent(evt)

move(x, y)

Move the widget

moveEvent(x, y)

Convenience function, Event Callback triggered after a successful move

name()

paintChildCanvas()

paintEvent(canvas)

Paint Event callback, this need to be overridden in the widget.

parentWidget()

pasteEvent(txt)

Callback triggered when a paste event is forwarded to this widget.

pos()

raiseWidget([raiseParent])

Raise the Widget above its relatives

resize(width, height)

Resize the widget

resizeEvent(w, h)

Handle resize events

setCurrentStyle(*args, **kwargs)

setDefaultSize(arg, width, height)

setDisabled([disabled])

This property holds whether the widget is disnabled

setDropEventProxy(proxy)

setEnabled([enabled])

This property holds whether the widget is enabled

setFocus()

Focus the widget

setFocusPolicy(policy)

This property holds the way the widget accepts keyboard focus

setGeometry(x, y, width, height)

Resize and move the widget

setMaximumHeight(maxh)

setMaximumSize(maxw, maxh)

setMaximumWidth(maxw)

setMinimumHeight(minh)

setMinimumSize(minw, minh)

setMinimumWidth(minw)

setName(name)

Set the name of this Instance

setParent(parent)

setStyle([style])

setToolTip(toolTip)

setVisible(visible)

Set the visibility status of this widget

setWidgetCursor([pos, type])

show()

show the widget

size()

style()

toolTip()

update([repaint, updateLayout, updateParent])

Update the widget and emit viewChanged signal if layout is updated

widgetItem()

width()

x()

y()

Methods Inherited from: TMouseEvents

enterEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse enter events for the widget.

leaveEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse leave events for the widget.

mouseDoubleClickEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse click events for the widget.

mouseDragEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse drag events for the widget.

mouseMoveEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse move events for the widget.

mousePressEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse press events for the widget.

mouseReleaseEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse release events for the widget.

mouseTapEvent(evt)

This event handler, can be reimplemented in a subclass to receive mouse click events for the widget.

wheelEvent(evt)

Handle mouse wheel events for scrolling

Methods Inherited from: TKeyEvents

keyEvent(evt)

This event handler, can be reimplemented in a subclass to receive key events for the widget.

Methods Inherited from: TDragEvents

dragEnterEvent(evt)

This event handler, can be reimplemented in a subclass to receive drag events for the widget.

dragLeaveEvent(evt)

This event handler, can be reimplemented in a subclass to receive drag events for the widget.

dragMoveEvent(evt)

This event handler, can be reimplemented in a subclass to receive drag events for the widget.

dropEvent(evt)

This event handler, can be reimplemented in a subclass to receive drag events for the widget.

TTkListWidget Attributes🌶️

classStyle

itemClicked

This signal is emitted whenever an item is clicked.

searchModified

This signal is emitted whenever the search text is modified.

textClicked

This signal is emitted whenever an item is clicked.