Implementing Stock Search Component in Qt with Preview and Keyboard Navigation

This implementation demonstrates a Qt-based stock search component that supports:

  • Fuzzy search by stock code or name
  • Interactive preview of search results
  • Mouse hover highlighting
  • Keyboard navigation (up/down arrows)
  • Context menu operations

Core Components

1. Custom Search Edit Control

The search input field extends QLineEdit to provide customized context menu functionality:

class StockSearchEdit : public QLineEdit
{
    Q_OBJECT
public:
    explicit StockSearchEdit(QWidget* parent = nullptr);
    
protected:
    void contextMenuEvent(QContextMenuEvent* event) override;
    
private:
    void setupContextMenu();
    QMenu* contextMenu = nullptr;
};

2. Search Preview Window

The preview window displays filterde results using a QTableView with custom delegate:

class StockPreview : public QTableView
{
    Q_OBJECT
public:
    StockPreview(QAbstractItemModel* model, QWidget* parent = nullptr);
    
    void highlightRow(int row);
    void moveSelectionUp();
    void moveSelectionDown();
    
protected:
    void mouseMoveEvent(QMouseEvent* event) override;
    
private:
    int currentHighlight = -1;
};

Implementation Details

Search Filtering

The component uses QSortFilterProxyModel for efficient filtering:

bool StockFilterModel::filterAcceptsRow(int row, const QModelIndex& parent) const
{
    QRegularExpression regex = filterRegularExpression();
    if(regex.pattern().isEmpty()) return true;
    
    for(int col = 0; col < 3; col++) {
        QModelIndex idx = sourceModel()->index(row, col, parent);
        if(sourceModel()->data(idx).toString().contains(regex)) {
            return true;
        }
    }
    return false;
}

Keyboard Navigation

Event filtering enables keyboard control of the preview:

bool StockWidget::eventFilter(QObject* watched, QEvent* event)
{
    if(watched == searchEdit && event->type() == QEvent::KeyPress) {
        QKeyEvent* keyEvent = static_cast<qkeyevent>(event);
        switch(keyEvent->key()) {
            case Qt::Key_Up: preview->moveSelectionUp(); return true;
            case Qt::Key_Down: preview->moveSelectionDown(); return true;
            case Qt::Key_Enter: 
            case Qt::Key_Return: emit stockSelected(); return true;
        }
    }
    return QWidget::eventFilter(watched, event);
}
</qkeyevent>

Preview Window Management

The preview appears/disapepars based on focus and content:

void StockWidget::onTextChanged(const QString& text)
{
    if(text.isEmpty()) {
        preview->hide();
    } else {
        filterModel->setFilterFixedString(text);
        if(filterModel->rowCount() > 0) {
            preview->show();
        }
    }
}

Tags: Qt QTableView QSortFilterProxyModel QLineEdit StockSearch

Posted on Wed, 02 Sep 2026 16:23:05 +0000 by sports