hdmjt
hdmjt

Reputation: 25

Add multiple trailing qactions to lineedit

I am trying to accomplish a lineEdit for text search & filtering, similar to those found in applications like vscode:

example from vscode

Qt's lineedit has a "in-build" clear button action that is similar to what I am looking for. I looked into qlineedits c++ source and build a modified function that adds a custom clear action. Is it possible to add multiple trailing actions next to one another to a lineedit similar to the example referenced above?

class ULineEdit(QtWidgets.QLineEdit):
    def __init__(self,
            defaultText: str = "",
            isReadOnly: bool = False,
            isClearButtonEnabled: bool = True,
            parent=None
            ):

        super(ULineEdit, self).__init__()
        self.setText(defaultText)
        self.setReadOnly(isReadOnly)

        self.setClearButtonEnabled(isClearButtonEnabled)

        self.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)

    # override When readOnly is set to QLineEdit it disables QToolButton (clear button)
    def setClearButtonEnabled(self, enable: bool = True):
        if enable == True:
            clearAction = UAction.UClearAction(parent=self)
            clearAction.triggered.connect(self.clear)
            self.textChanged.connect(clearAction.dynamicVisibility)
            self.addAction(clearAction, QtWidgets.QLineEdit.TrailingPosition)
            # default state
            clearAction.dynamicVisibility(self.text())
        else:
            clearAction = UAction.getClearAction(self)
            if clearAction is not None:
                self.removeAction(clearAction)

Upvotes: 1

Views: 322

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

You have to use the addAction() method of QLineEdit:

from PyQt5 import QtWidgets


class ULineEdit(QtWidgets.QLineEdit):
    def __init__(
        self,
        defaultText: str = "",
        isReadOnly: bool = False,
        isClearButtonEnabled: bool = True,
        parent=None,
    ):

        super(ULineEdit, self).__init__()
        self.setText(defaultText)
        self.setReadOnly(isReadOnly)

        self.setClearButtonEnabled(isClearButtonEnabled)

        self.setSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed
        )

        foo_action = QtWidgets.QAction(self)
        icon = self.style().standardIcon(QtWidgets.QStyle.SP_DesktopIcon)
        foo_action.setIcon(icon)
        self.addAction(foo_action, QtWidgets.QLineEdit.TrailingPosition)

        bar_action = QtWidgets.QAction(self)
        icon = self.style().standardIcon(QtWidgets.QStyle.SP_DirIcon)
        bar_action.setIcon(icon)
        self.addAction(bar_action, QtWidgets.QLineEdit.TrailingPosition)


def main():
    app = QtWidgets.QApplication([])
    w = ULineEdit()
    w.show()
    app.exec_()


if __name__ == "__main__":
    main()

enter image description here

Upvotes: 1

Related Questions