Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide multiple links in one cell of a QTableView

I have a QTableView in my project, in which several columns display data that includes a hyperlink. I use a delegate class for these to set it up so that when the cell in the column is clicked, it opens the linked page in the browser. This works great... when it's only one value being linked to one page. For example, I may have a list of search values for mysite.com where the columns have values A, B, C, etc.. If the user clicks on the cell in this column with A, it will open a hyperlink for mysite.com/A (again, this part works fine). However, I now need to add a column that may have something like "A,B", where it needs to support links to search for A AND B in the same cell depending on which they click. I've been searching around online for a while now and it seems like this probably can't be done with a delegate. I have a line in a QTextBrowser elsewhere in my code where I can do this via HTML, like this:

QString toShow;
for(int i = 0; i < searchValueList.size(); i++)
{
  toShow.append("`<a href=\"www.mysite.com/" + searchValueList.at(i) + "\"`>" +
    searchValueList.at(i) + "`</a`>";
}

However I can't find any way to set the cells in a QTableView to recognize HTML formatting or Rich Text, and alas I'm not even sure that's possible. Is there any way at all to do what I'm trying to accomplish?

like image 981
thnkwthprtls Avatar asked Mar 19 '23 22:03

thnkwthprtls


1 Answers

You can create a custom QItemDelegate for the specific column in which you can display rich text. The delegate could be like :

class RichTextDelegate: public QItemDelegate
{
public:
    RichTextDelegate(QObject *parent = 0);

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

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

void RichTextDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{

    if( option.state & QStyle::State_Selected )
        painter->fillRect( option.rect, option.palette.highlight() );


    painter->save();

    QTextDocument document;
    document.setTextWidth(option.rect.width());
    QVariant value = index.data(Qt::DisplayRole);
    if (value.isValid() && !value.isNull())
    {
                document.setHtml(value.toString());
                painter->translate(option.rect.topLeft());
                document.drawContents(painter);

    }

    painter->restore();
}

You should set the item delegate for the specific column :

ui->tableView->setItemDelegateForColumn(colIndex, new RichTextDelegate(ui->tableView));

Now if you set the model text for the specific column in a row to a rich text, it will be shown properly :

model->item(rowIndex,  colIndex)->setText(someRichText);
like image 85
Nejat Avatar answered Apr 28 '23 08:04

Nejat