Search code examples
pythonpyqtpyqt5qtstylesheetsqcompleter

change style of QCompleter?


I try to aplicate a stylesheet in a QLineEdit in especific in a popup of QCompleter.

in QtDesigner try:

enter image description here

code:

QLineEdit#lineEdit::popup{
background:red;
}

but it does not work

What I'm looking for is to change the color of the letter, background color and alignment of the letter that appears in the box with the suggestions

try also on QtDesigner

QAbstractItemView {}
QAbstractItemView :: item {}

to change the visual properties of the list of suggestions that is displayed in the QLineEdit but they do not work

in my code try:

from PyQt5.QtWidgets import QMainWindow,QApplication, QCompleter
from PyQt5 import QtCore
from PyQt5 import uic



class Pricnipal(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        uic.loadUi("uno.ui",self)

        completer = QCompleter()

        self.lineEdit.setCompleter(completer)
        model = QtCore.QStringListModel()
        completer.setModel(model)
        self.get_data(model)
    def get_data(self,model):
        model.setStringList(["uno","dos","tres","cuatro","este es mi nombre"])


app  = QApplication([])
p = Pricnipal()
p.show()
app.exec_()

Solution

  • You have to use a delegate:

    from PyQt5 import QtCore, QtGui, QtWidgets, uic
    
    class CompleterDelegate(QtWidgets.QStyledItemDelegate):
        def initStyleOption(self, option, index):
            super(CompleterDelegate, self).initStyleOption(option, index)
            option.backgroundBrush = QtGui.QColor("red")
            option.palette.setBrush(QtGui.QPalette.Text, QtGui.QColor("blue"))
            option.displayAlignment = QtCore.Qt.AlignCenter
    
    class Principal(QtWidgets.QMainWindow):
        def __init__(self):
            super(Principal, self).__init__()
            uic.loadUi("uno.ui",self)
            completer = QtWidgets.QCompleter(self)
            self.lineEdit.setCompleter(completer)
            model = QtCore.QStringListModel()
            completer.setModel(model)
            delegate = CompleterDelegate(self.lineEdit)
            completer.popup().setStyleSheet("background-color:red;")
            completer.popup().setItemDelegate(delegate)
            self.get_data(model)
    
        def get_data(self,model):
            model.setStringList(["uno","dos","tres","cuatro","este es mi nombre"])
    
    if __name__ == '__main__':
        import sys
        app  = QtWidgets.QApplication(sys.argv)
        p = Principal()
        p.show()
        sys.exit(app.exec_())