Reputation: 143
I'm using QTreeView as view and QAbstractItemModel as model.
This is how my app looking right now:
I want to make this field(url) on the right view clickable, not editable, so user can click on it and open url.
XML:
<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
<name>Hospitality</name>
<author>Orion</author>
<url>https://ludeon.com/forums/index.php?topic=11444.0</url>
<targetVersion>0.14.1241</targetVersion>
</ModMetaData>
Kind regards, Maxim.
Upvotes: 0
Views: 1024
Reputation: 244291
The first thing we do is disable the editing of the items with
{your treeview}.setEditTriggers(QAbstractItemView.NoEditTriggers)
Then we connect the clicked event to a slot (in my case on_clicked), from the QModelIndex we get the Item, and consequently the text associated with the latter, we then launch the opening Url with:
QDesktopServices.openUrl(QUrl({your url}))
Complete code:
import sys
from PyQt5.QtCore import QFile, QIODevice, QUrl
from PyQt5.QtGui import QDesktopServices, QStandardItem, QStandardItemModel
from PyQt5.QtWidgets import QAbstractItemView, QApplication, QTreeView
from PyQt5.QtXml import QDomDocument
class CustomTreeView(QTreeView):
def __init__(self, parent=None):
super(CustomTreeView, self).__init__(parent=parent)
self.mdl = QStandardItemModel()
self.mdl.setHorizontalHeaderLabels(["tag", "value"])
self.setModel(self.mdl)
self.readXML('item.xml')
self.clicked.connect(self.on_clicked)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
def on_clicked(self, index):
text = self.mdl.itemFromIndex(index).text()
QDesktopServices.openUrl(QUrl(text))
def readXML(self, filename):
doc = QDomDocument("doc")
file = QFile(filename)
if not file.open(QIODevice.ReadOnly):
return
if not doc.setContent(file):
file.close()
return
file.close()
rootNode = self.mdl.invisibleRootItem()
docElem = doc.documentElement()
node = docElem.firstChild()
while not node.isNull():
element = node.toElement()
if not element.isNull():
tag = QStandardItem(element.tagName())
value = QStandardItem(element.text())
# tag.setEditable(False)
# value.setEditable(False)
rootNode.appendRow([tag, value])
node = node.nextSibling()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = CustomTreeView()
w.show()
app.exec_()
Upvotes: 1