在光标后面弹出

1
2
3
4
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0)
+ c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr);

TAG

在自动补全的后面添加一个用来标志类别的小tag

1
2
3
4
5
6
7
8
9
10
QStandardItemModel *m = new QStandardItemModel(words.count(), 2, completer); // 设置为两列
for (int i = 0; i < words.count(); ++i) {
QModelIndex countryIdx = m->index(i, 0);
QModelIndex symbolIdx = m->index(i, 1);
QString country = words[i].mid(0, words[i].length() - 2).trimmed();
QString symbol = words[i].right(2);
m->setData(countryIdx, country);
m->setData(symbolIdx, symbol);
}
completer->setModel(m);

Model 示例

文件路径全部显示的model

1
2
3
4
5
6
class FileSystemModel : public QFileSystemModel
{
public:
FileSystemModel(QObject *parent = 0);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
FileSystemModel::FileSystemModel(QObject *parent)
: QFileSystemModel(parent)
{
}
QVariant FileSystemModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole && index.column() == 0) {
QString path = QDir::toNativeSeparators(filePath(index));
if (path.endsWith(QDir::separator()))
path.chop(1);
return path;
}

return QFileSystemModel::data(index, role);
}

焦点设置

1
2
3
4
5
void TextEdit::focusInEvent(QFocusEvent *e)
{
if (c) c->setWidget(this);
QTextEdit::focusInEvent(e);
}

选中事件

1
2
3
4
5
6
7
8
9
10
void MainWindow::sloHighlight(const QModelIndex &index)
{
QAbstractItemModel *completionModel = completer->completionModel();
QAbstractProxyModel *proxy = qobject_cast<QAbstractProxyModel *>(completionModel);
if (!proxy)
return;
QModelIndex sourceIndex = proxy->mapToSource(index);
treeView->selectionModel()->select(sourceIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
treeView->scrollTo(index);
}