【问题标题】:change style of QCompleter?改变 QCompleter 的风格?
【发布时间】:2019-05-08 20:09:32
【问题描述】:

我尝试在 QCompleter 的弹出窗口中特别指定 QLineEdit 中的样式表。

在 QtDesigner 中尝试:

代码:

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

但它不起作用

我正在寻找的是更改字母的颜色、背景颜色和显示在建议框中的字母的对齐方式

也试试 QtDesigner

QAbstractItemView {}
QAbstractItemView :: item {}

更改 QLineEdit 中显示的建议列表的视觉属性,但它们不起作用

在我的代码中尝试:

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_()

【问题讨论】:

    标签: python pyqt pyqt5 qtstylesheets qcompleter


    【解决方案1】:

    您必须使用委托:

    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_())
    

    【讨论】:

    • 直接在Qt Designer中可以不应用效果吗?
    • @Mystic_Force 不,你不能在 Qt Designer 中
    猜你喜欢
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2015-06-23
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多