5

With the help of python, I managed to build a small script that replaces all URLs in a text column with images using a delegate. The images where loaded from Microsoft SharePoint using an adapted version of request_ntlm.

import PyQt4
from PyQt4 import QtGui,QtCore
import requests
from requests_ntlm import HttpNtlmAuth, HttpNtlmSspiAuth
from PyQt4.QtGui import QApplication, QTableView

class ImageDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent):
        QtGui.QStyledItemDelegate.__init__(self, parent)

    def paint(self, painter, option, index):
        # Get Item Data
        url = index.model().data(index, QtCore.Qt.EditRole)

        if url != '':
            style = QtGui.QApplication.style()
            opt = QtGui.QStyleOptionGraphicsItem()
            opt.rect = option.rect
            r = requests.get(url, auth=HttpNtlmSspiAuth())
            data = r.content

            pixmap = QtGui.QPixmap()
            pixmap.loadFromData(data)
            if option.rect.x() > 250:
                pixmap=pixmap.scaledToWidth(250)

            painter.drawPixmap(option.rect.x(), option.rect.y(),  pixmap)


dialog = iface.showAttributeTable(iface.activeLayer())
targetColumnIndex = 8 # how to find Index of column?
delegateImage = ImageDelegate(iface)

dialog.findChildren(QTableView)[0].setItemDelegateForColumn(targetColumnIndex, delegateImage)
dialog.findChildren(QTableView)[0].setColumnWidth(targetColumnIndex, 250 )
dialog.findChildren(QTableView)[0].verticalHeader().setDefaultSectionSize(200)

What I couldn't manage by now: how to retrieve the index of a given column (see hardcoded targetColumnIndex in the code above) in the attribute table (QTableView) even when "colxy" is moved or some columns are hidden?

2

If someone is interested, here's the answer:

dialog = iface.showAttributeTable(iface.activeLayer())

delegateImage = ImageDelegate(iface)
tableView = dialog.findChildren(QTableView)[0]
model = tableView.horizontalHeader().model()
for column in range(model.columnCount()):
    title = tableView.model().children()[0].headerData(column,QtCore.Qt.Horizontal,0)
    if title == 'colxy':
        targetColumnIndex = column
        break

Unfortunately, that brings me only a little step further.

Next question that comes to mind:
How can I respond to any index change of the image column? (i.e. when other columns are hidden or the column is moved) Are there any signals available? Or can I disable the context menu of the table header?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.