如何在QCompleter的项目之间画一条线作为分隔符?

时间:2013-12-28 13:40:22

标签: c++ qt qtgui qlineedit qcompleter

我有一个QCompleter和一个QStringListModel设置为QCompleter。现在,我如何在设置为QStringListModel的StringList项之间绘制一条线作为分隔符。最后,QCompleter将设置为QLineEdit。 enter image description here

2 个答案:

答案 0 :(得分:0)

使用新类型创建自定义模型,并在委托绘制中为窗口小部件创建自定义委托,您可以在新类型中绘制任何内容并允许在父级中绘制默认类型... see this example for combobox

答案 1 :(得分:0)

好的,所以我试图提供比我最初的提示更多的细节,因为我认为这就足够了。我担心人们会开始进一步询问,所以这就是它:

completerseparatordelegate.h

#include <QItemDelegate>
#include <QSize>
#include <QModelIndex>
#include <QStyleOptionViewItem>

class CompleterSeparatorDelegate : public QItemDelegate
{
    Q_OBJECT

public:
    CompleterSeparatorDelegate(QObject *parent = 0);
    ~CompleterSeparatorDelegate();

protected:    
    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index) const;
    QSize sizeHint(const QStyleOptionViewItem &option,
                   const QModelIndex &index) const;
};

completerseparatordelegate.cpp

#include "completerseparatordelegate.h"

#include <QPainter>
#include <QString>

CompleterSeparatorDelegate::CompleterSeparatorDelegate(QObject *parent)
    : QItemDelegate(parent)
{
}

CompleterSeparatorDelegate::~CompleterSeparatorDelegate()
{
}

void CompleterSeparatorDelegate::paint(QPainter *painter,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
{
    if(index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator"))
    {
        painter->setPen(Qt::red);
        painter->drawLine(option.rect.left(), option.rect.center().y(), option.rect.right(), option.rect.center().y());
    } else {
        QItemDelegate::paint(painter, option, index);
    }
}

QSize CompleterSeparatorDelegate::sizeHint(const QStyleOptionViewItem &option,
                                           const QModelIndex &index) const
{
    QString type = index.data(Qt::AccessibleDescriptionRole).toString();
    if(type == QLatin1String("separator"))
        return QSize(0, 2);
    return QItemDelegate::sizeHint( option, index );
}

mainwindow.cpp

#include "completerseparatordelegate.h"

...
listView->setItemDelegate(new CompleterSeparatorDelegate);
completer->setPopup(listView);
...

我没有尝试编译这段代码,因为我只是将其作为原始文本动态编写,但主要思想基本上来自here并进行了少量修改。