Frage

Using Qt, I've created a gui that includes a QListView widget.

This widget is being fed data from a QStandardItemModel object that is made with two columns:

  1. Description;
  2. and Hyperlink

What I'm trying to do is to actually have the description there with a hyperlink that opens the page in the QListView using whatever the user's default browser is.

What I've tried so far is to actually build the Data using HTML, however this only produced the pure HTML text non-rendered.

Can anyone help?

Edited to show the code used:

Code used to build the Model:

QStandardItemModel * model = new QStandardItemModel;
for(int i =0; i < newsItems.size(); i++)
{
    QList<QStandardItem *> rowItems;
    rowItems.append(new QStandardItem("Description"));
    rowItems.append(new QStandardItem("http://somesite.com"));

    model->appendRow(rowItems);
}

Code used by a 'QPushButton' to use the model

//The cTicExt.getTickerNews(strTicker)  simply returns the QStandardItemModel created above
ui->listView_News->setModel(cTicExt.getTickerNews(strTicker));
War es hilfreich?

Lösung

I think you can do this without model:

//ListWidget.h
#pragma once
#include <QListWidget>
#include <QListWidgetItem>
#include <QLabel>
#include <QUrl>
#include <QDesktopServices>

class ListWidget: public QListWidget
{
  Q_OBJECT

public:
  ListWidget()
  {
    QListWidgetItem* item = new QListWidgetItem("", this);
    addItem(item);
    QString description("Description:");
    QString hyperlinkText("http://www.stackoverflow.com/");
    QLabel* hyperlinkWidget = new QLabel( QString("<span>%1&nbsp;&nbsp;</span><a href=\"%2\">%2</a>").arg(description).arg(hyperlinkText), this);
    setItemWidget(item, hyperlinkWidget);

    connect(hyperlinkWidget, SIGNAL(linkActivated(const QString&)), this, SLOT(onHyperlinkActivated(const QString&)));
  }

private slots:
  void onHyperlinkActivated(const QString & link)
  {
    QDesktopServices::openUrl( QUrl(link) );
  }
};

//main.cpp
#include <QtWidgets/QApplication>
#include "ListWidget.h"

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);

  ListWidget w;
  w.show();

  return a.exec();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top