PDA

View Full Version : Delegate hyperlink



migel
8th September 2011, 00:44
Hi

I am using below code to draw an html. I need to display text in the item as link, once clicked on a text (not on the item it self) it perform some action. I was using setIndexWidget and QLabel but performance is pretty bad.

An here the question how to make a text clickable ( not the item) to behave like an html link.

Possible ? thanks for help


QSize HyperLinkDelegate::sizeHint(const QStyleOptionViewItem & option ,
const QModelIndex & index) const
{
QStyleOptionViewItemV4 optionV4 = option;
initStyleOption(&optionV4, index);

QTextDocument doc;
doc.setHtml(optionV4.text);
doc.setTextWidth(optionV4.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}

void HyperLinkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItemV4 optionV4 = option;
initStyleOption(&optionV4, index);

QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();

QTextDocument doc;
doc.setHtml(optionV4.text);

// Painting item without text
optionV4.text = QString();
style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter);

QAbstractTextDocumentLayout::PaintContext ctx;

// Highlighting text if item is selected
if (optionV4.state & QStyle::State_Selected)
ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));

QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
painter->save();
painter->translate(textRect.topLeft());
painter->setClipRect(textRect.translated(-textRect.topLeft()));
doc.documentLayout()->draw(painter, ctx);
painter->restore();

}

wysota
8th September 2011, 00:53
There are no magic two lines of code you can call and have the job done. You have to calculate the geometry of the link and provide event handlers for the mouse that will 1) change the cursor when it is over the link and 2) execute the action when the link is clicked.