Qt: Customizing QCompleter

At first, formulate the model,

//For Completer
QStandardItemModel* SoftCallController::GetContactCompleterModel()
{
    QStandardItemModel *completerModel = new QStandardItemModel();
    QByteArray temp;
    auto buddyList = _buddyRepo.GetAllBuddy(0);
    for(QList<CBuddy>::iterator i = buddyList.begin(); i != buddyList.end(); i++)
    {
        completerModel->setItem(i - buddyList.begin(), 1, new QStandardItem((*i).getSipUsername()));
        completerModel->setItem(i - buddyList.begin(), 2, new QStandardItem((*i).getDisplayName()));
 
        temp = (*i).getPhoto();
        QPixmap* pixmap = new QPixmap();
        pixmap->loadFromData(temp);
        *pixmap = pixmap->scaledToHeight(20);
        *pixmap = pixmap->scaledToWidth(20);
        QStandardItem* imageData = new QStandardItem();
        imageData->setData(QPixmap(*pixmap), Qt::DecorationRole);
 
        completerModel->setItem(i - buddyList.begin(), 0, imageData);
 
    }
    return completerModel;
}

Customized completer

Then, comes the rendering part

void ContactList::initCompleter(QStandardItemModel *completerModel)
{
    QCompleter *completer = new QCompleter(completerModel, ui->tbPhoneNumber);
    completer->setCompletionColumn(1);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setMaxVisibleItems(20);
    completer->setCompletionMode(QCompleter::PopupCompletion);
 
    QTableView *tableView = new QTableView();
    tableView->verticalHeader()->setVisible(false);
    tableView->horizontalHeader()->setVisible(false);
    tableView->setSelectionBehavior(QTableView::SelectRows);
    tableView->setShowGrid(false);
    tableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    tableView->horizontalHeader()->setStretchLastSection(true);
    //tableView->resizeColumnsToContents();
    //tableView->resizeRowsToContents();
    completer->setPopup(tableView);
 
    ui->tbPhoneNumber->setCompleter(completer);
}

Leave a Reply

Your email address will not be published. Required fields are marked *