#!/usr/bin/env python3
from PyQt5 import QtCore, QtWidgets
from qtypy.widgets.taglist import TagList
from qtypy.model import PythonListModel
class StringListModel(PythonListModel):
def data(self, index, role):
text = super().data(index, QtCore.Qt.UserRole)
if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
return text
def flags(self, index):
flags = super().flags(index)
if index.row() == 0:
return int(flags)
flags = int(flags | QtCore.Qt.ItemIsEditable)
if index.row() == 1:
pass
if index.row() in (2, 4):
flags |= TagList.ItemIsClosable
if index.row() in (3, 4):
flags |= TagList.ItemHasMenu
return flags
def setData(self, index, role, text):
self[index.row()] = text
class MyTagList(TagList):
def __init__(self, parent):
super().__init__(StringListModel(value=['read only', 'editable', 'deletable', 'menu', 'both']), parent)
cmpl = QtWidgets.QCompleter(['one', 'two', 'three', 'four'])
self.setCompleter(cmpl)
def addTag(self, text):
self.model().append(text)
def removeTag(self, index):
self.model().pop(index)
def popupMenu(self, index, pos):
menu = QtWidgets.QMenu(self)
menu.addSection(self.model()[index])
menu.addSeparator()
menu.addAction('Action #1')
menu.addAction('Action #2')
menu.popup(pos)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
container = QtWidgets.QWidget(self)
layout = QtWidgets.QFormLayout()
layout.addRow('Tags', MyTagList(self))
layout.addRow('Whatever', QtWidgets.QLabel('spam'))
layout.setFieldGrowthPolicy(layout.ExpandingFieldsGrow)
container.setLayout(layout)
self.setCentralWidget(container)
self.resize(800, 600)
self.show()
self.raise_()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
win = MainWindow()
app.exec_()