Tre*_*out 8 c++ url qt qt4 qtableview
什么是提供一个最好的办法可点击的URL QTableView(或者QTreeView,QListView等...)
给定QStandardItemModel一些列包含带有URL的文本的位置,我希望它们可以变为可点击,然后通过使用来处理单击QDesktopServices::openURL()
我希望有一些简单的方法来利用QLabeltextInteraction标志并将它们塞进表中.我无法相信没有更简单的方法来处理这个问题.我真的希望我错过了一些东西.
你需要创建一个委托来进行绘画.代码看起来应该是这样的:
void RenderLinkDelegate::paint(
QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index
) const
{
QString text = index.data(Qt::DisplayRole).toString();
if (text.isEmpty())
return;
painter->save();
// I only wanted it for mouse over, but you'll probably want to remove
// this condition
if (option.state & QStyle::State_MouseOver)
{
QFont font = option.font;
font.setUnderline(true);
painter->setFont(font);
painter->setPen(option.palette.link().color());
}
painter->drawText(option.rect, Qt::AlignLeft | Qt::AlignVCenter, text);
painter->restore();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
好吧,您可以使用委托在qtableview中呈现富文本,并使用自定义委托重新实现paint方法,例如:
void CHtmlDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt(option);
QLabel *label = new QLabel;
label->setText(index.data().toString());
label->setTextFormat(Qt::RichText);
label->setGeometry(option.rect);
label->setStyleSheet("QLabel { background-color : transparent; }");
painter->translate(option.rect.topLeft());
label->render(painter);
painter->translate(-option.rect.topLeft());
}
Run Code Online (Sandbox Code Playgroud)
但是,它不会使超链接可单击.
为此,您可以使用以下hack.重新实现表/列表视图的setModel方法并使用setIndexWidget.
void MyView::setModel(QAbstractItemModel *m)
{
if (!m)
return;
QTableView::setModel(m);
const int rows = model()->rowCount();
for (int i = 0; i < rows; ++i)
{
QModelIndex idx = model()->index(i, 1);
QLabel *label = new QLabel;
label->setTextFormat(Qt::RichText);
label->setText(model()->data(idx, CTableModel::HtmlRole).toString());
label->setOpenExternalLinks(true);
setIndexWidget(idx, label);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我用qlabels替换了第1列.请注意,您需要使模型中的显示角色无效以避免重叠数据.
无论如何,我会对基于代表的更好的解决方案感兴趣.