QTableWidget Highlight Partial Text



  • Hello all,

    I have a search box (QLineEdit) and a QTableWidget. Now suppose if I enter the word "xyz" in search box than if any QTablewidget cell contains that specific text i.e. "xyz", I want to highlight that part of the text with yellow color. (ctrl+f behavior in QT).

    Please help. I have tried many ways to do this, but not succeeded yet.

    Thanks.



  • it's not crazy difficult, you just need to subclass QStyledItemDelegate, add a member to hold the string and reimplement the paint method to do the highlight



  • @VRonin

    I am trying to do this. I am a newbiew, so need your assistance. Hope you can understand. Here are some rough code.

    MediaFileItemDelegate::MediaFileItemDelegate(QObject *parent) :QStyledItemDelegate(parent)
    {
    
    }
    
    MediaFileItemDelegate::~MediaFileItemDelegate()
    {
    
    }
    
    void MediaFileItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,const QModelIndex& index) const
    {
        QString str = qvariant_cast<QString>(index.data());
    
        painter->save();
    
        painter->setPen(Qt::NoPen);
    
       // painter->drawRect(option.rect);
    
        if(index.data().toString().contains("xyz"))
        {
            painter->setPen(Qt::blue);
            painter->drawText(option, str);
        }
        else
        {
            QStyledItemDelegate::paint(painter, option, index);
        }
    
        painter->restore();
    }
    

    Currently this code is highlighting the whole text (example: My name is xyz) and I am doing manually matching. So how can i select only xyz. Thanks


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.