在使用QCompleter,一般都会面临两个问题:1、如何设置Completer的行高;2、如何设置Completer的样式。本文将一次为你解答,顺便讲讲ComboBox设置Completer时需要注意的事项。
1、设置QCompleter行高
如果你打算像QComboBox设置下拉框样式的方式(comboBox->setView(new QListView()))来处理行高的问题,发现不会生效。设置QCompleter的行高,只能通过代理的方式实现,代码如下:
class ComboBoxDelegate : public QItemDelegate
{
public:
explicit ComboBoxDelegate(QObject * parent = nullptr) : QItemDelegate(parent) {}
~ComboBoxDelegate() = default;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QSize size = QItemDelegate::sizeHint(option, index);
size.setHeight(32);
return size;
}
};
如何使用ComboBoxDelegate,代码如下:
QAbstractItemView* view = comboxCompleter->popup();
view->setItemDelegate(new ComboBoxDelegate());
2、设置QCompleter样式
comboxCompleter->popup()->verticalScrollBar()->setStyleSheet(
"QScrollBar:vertical{background: #e2e3e4; width: 16px; margin: 16px 0px 16px 0px;}"
"QScrollBar::handle:vertical{background: #3A72D8;}"
"QScrollBar::handle:vertical:hover{background: #4d96fe;}"
"QScrollBar::handle:vertical:pressed{background: #014cb6;}"
"QScrollBar::add-line:vertical{background: pink; height: 16px; subcontrol-position: bottom; subcontrol-origin: margin;}"
"QScrollBar::sub-line:vertical{background: red; height: 16px; subcontrol-position: top; subcontrol-origin: margin;}"
"QScrollBar:down-arrow:vertical{width: 10px; height: 10px; background: transparent; image: url(:/res/box_down.svg);}"
"QScrollBar:up-arrow:vertical{width: 10px; height: 10px; background: transparent; image: url(:/res/box_up.svg);}"
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {background: none;}");
comboxCompleter->popup()->setStyleSheet("QListView{background-color: #FFFFFF;"
"color: #353637;"
"selection-background-color: #3A72D8;"
"selection-color: white;"
"show-decoration-selected: 1;"
"font-size: 14pt;"
"font-family: microsoft yahei;");
3、QComboBox设置QCompleter需要注意的地方
记住先后顺序:一定是先初始化QComboBox,然后再设置QCompleter。
否则可能会导致在ComboBox输入时,Completer不会弹出的问题,即使你设置了setCompletionMode(QCompleter::PopupCompletion)。
QStringList userList;
for (int i=0; i<20; i++) {
QString item = "name_" + QString::number(i);
userList.append(item);
}
combox->addItems(userList);
combox->setEditable(true);
combox->lineEdit()->setPlaceholderText(tr("Enter name"));
combox->setInsertPolicy(QComboBox::NoInsert);
combox->setCurrentIndex(-1);
QCompleter *comboxCompleter = new QCompleter(userList, this);
comboxCompleter->setMaxVisibleItems(5);
comboxCompleter->setCaseSensitivity(Qt::CaseInsensitive);
comboxCompleter->setCompletionMode(QCompleter::PopupCompletion);
comboxCompleter->setFilterMode(Qt::MatchContains);
comboxCompleter->setCompletionColumn(combox->modelColumn());
QAbstractItemView* view = comboxCompleter->popup();
view->setItemDelegate(new ComboBoxDelegate());
combox->setCompleter(comboxCompleter);
4、效果图
为了对比,没有设置QComboBox的样式,只处理了QCompleter样式,效果如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)