I am having issues with .deleter where the values I am trying to delete only works for the first try.
To replicate:
Checked 'GrpB-Alice' and hit 'Click Me' (Do not close the window yet)
i.myDict returns {u'GrpB': set([u'Alice'])}) which is correct
Checked 'GrpB-Phan' and hit 'Click Me'
i.myDict returns {u'GrpB': set([u'Alice', 'Phan])}) which is correct
Checked 'GrpB-Alice' and hit 'Click Me'
i.myDict returns {u'GrpB': set([u'Alice', 'Phan])}) which is incorrect where I am expecting {u'GrpB': set([u'Alice'])})
If I close the tool, and redo the last step, only will i.myDict returns correctly, but should I checked on new options, at the third time, i.myDict will returns incorrect result again.
The deleter is definitely being called but it only seems to execute the real deletion once though. Am I missing something here?
class SubMenuWindow(QtGui.QWidget):
def __init__(self, menu_items, parent=None, callback=None):
super(SubMenuWindow, self).__init__(parent)
self.callback = callback
self.my_lyt = QtGui.QVBoxLayout()
self.checked_options = []
self.sel = defaultdict(set)
for menu_name, submenu_name in menu_items.items():
# Set the main menu item name
self.groupbox = QtGui.QGroupBox(self)
self.groupbox.setTitle(menu_name)
self.groupbox.setLayout(QtGui.QVBoxLayout())
self.my_lyt.addWidget(self.groupbox)
if submenu_name:
sub_txt = [action for action in submenu_name]
for s in sub_txt:
sub_chk = QtGui.QCheckBox(s)
self.checked_options.append(sub_chk)
self.groupbox.layout().addWidget(sub_chk)
apply_tag_btn = QtGui.QPushButton('Apply to selected item')
apply_tag_btn.clicked.connect(self.get_checked_options)
self.my_lyt.addWidget(apply_tag_btn)
self.my_lyt.addStretch()
self.setLayout(self.my_lyt)
self.show()
def get_checked_options(self):
for chk in self.checked_options:
if chk.isChecked():
print 'Checked - {0}, Parent - {1}'.format(chk.text(), chk.parent().title())
self.sel[chk.parent().title()].add(chk.text())
if self.callback:
self.callback()
class MainWin(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWin, self).__init__(parent)
self.my_dict = {}
btnA = QtGui.QPushButton('Click Me')
btnA.clicked.connect(self.get_options)
btnB = QtGui.QPushButton('Get results')
btnB.clicked.connect(self.get_results)
layout = QtGui.QVBoxLayout()
layout.addWidget(btnA)
layout.addWidget(btnB)
self.setLayout(layout)
def get_options(self):
sample_dict = {'GrpA' : ['John', 'Zack'], 'GrpB' : ['Alice', 'Phan']}
self.subWin = SubMenuWindow(sample_dict, callback=self.get_results)
def get_results(self):
i = MyDict()
# delete any existing values
del (i.myDict)
# append the new values
i.myDict = self.subWin.sel
print 'current myDict values : ', i.myDict
# If I select 'GrpB - Alice'
# i.myDict is `{u'GrpB': set([u'Alice'])})` # correct
# If I select 'GrpB - Alice' and 'GrpB - Phan'
# i.myDict is `{u'GrpB': set([u'Alice', 'Phan'])})` # correct
# If I re-select 'GrpB - Alice'
# i.myDict is `{u'GrpB': set([u'Alice', 'Phan'])})` # in-correct
class MyDict(QtCore.QObject):
def __init__(self):
self._myDict = None
#property
def myDict(self):
return self._myDict
#myDict.setter
def myDict(self, value):
self._myDict = value
#myDict.deleter
def myDict(self):
del(self._myDict)
Related
I set the number of spinboxes in the previous window and then, according to the code below, they are added in the next window, but when I click the button, I need to pick up the value from each generated spinbox, but at the moment the value is transmitted only from the last one.
How do I get the value from each spinbox?
Thank you!
class CreateSpuWindow(QMainWindow):
def __init__(self, value):
super().__init__()
uic.loadUi('ui/statement_spu_1.ui', self)
self.value = value # Quantity pf spinBoxes
for i in range(value):
self.spu_label = QLabel(self)
self.spu_label.setText(f"SPU №{i+1}. PP:")
self.quantity_pp = QSpinBox(self)
self.quantity_pp.setValue(1)
self.quantity_pp.setMinimum(1)
self.gridLayout_2.addWidget(self.spu_label, 2 * i, 0)
self.gridLayout_2.addWidget(self.quantity_pp, 2 * i, 1)
self.next_tu_spu_2Button.clicked.connect(self.next_wind_spu_btn)
self.back_btn.clicked.connect(self.back_btn_cl)
def next_wind_spu_btn(self):
data = []
# Get a value from spinbox
for i in str(self.quantity_pp.value()):
data.append(i)
print(data)
quantity_spu = self.value
self.ReadyTableSpuWindow = ReadyTableSpuWindow(quantity_spu)
self.ReadyTableSpuWindow.show()
self.close()
def back_btn_cl(self):
self.close()
self.QuantitySpuWindow = QuantitySpuWindow()
self.QuantitySpuWindow.show()
I have a QTableView/QAbstractTableModel framework where I implemented a context menu, with at most 2 actions, depending on the index where the menu was requested. For one of those two actions, once triggered I would like to emit the index where the context menu was requested. I have a solution that works but I don't like it.
The code:
class MyModel(QAbstractTableModel):
...
def _restore_all(self):
print('restore all')
def _restore_index(self, index):
print('restore index at: row = ' , index.row(), ', column = ', index.column())
...
class _ItemAwareAction(QAction):
_mytriggered = pyqtSignal('QModelIndex')
def __init__(self, *args, index=None, **kwargs):
super().__init__(*args, **kwargs)
self._index = index
self.triggered.connect(self._emit_index)
def _emit_index(self):
self._mytriggered.emit(self._index)
class MyTableView(QTableView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setContextMenuPolicy(Qt.CustomContextMenu)
model = MyModel(self)
self.setModel(model)
# Attributes
restore_all_action = QAction('Restore all values', self)
self._restore_all_action = restore_all_action
self._menu = QMenu(self)
# Connexions
self.customContextMenuRequested.connect(self._item_context_menu)
restore_all_action.triggered.connect(model._restore_all)
def _item_context_menu(self, pos):
menu = self._menu
menu.clear()
index = self.indexAt(pos)
model = self.model()
originals = model._originals
if not originals:
return
menu.addAction(self._restore_all_action)
references = model._index_to_references(index)
if references in originals:
action = _ItemAwareAction(
'Restore this value', parent=self, index=index
)
action._mytriggered.connect(model._restore_index)
menu.addAction(action)
menu.popup(self.viewport().mapToGlobal(pos))
...
I find my _ItemAwareAction class to be an unnecessary loop. Maybe you can point me to a simpler and more straightforward solution.
The simpler solution would be to use lambda or partials:
def _item_context_menu(self, pos):
# ...
if references in originals:
action = QAction('Restore this value', parent=self)
action.triggered.connect(lambda: model._restore_index(index))
# ...
Since you're not doing cycles of sort, you could even just check if the triggered action is the one that should reset, and that's accomplished by using exec() (which blocks until the menu is triggered/closed) instead of returning immediately:
def _item_context_menu(self, pos):
# ...
if references in originals:
restoreAction = QAction('Restore this value', parent=self)
else:
# cancelled menu returns None, we need to compare with something else
restoreAction = -1
if menu.exec_(self.viewport().mapToGlobal(pos)) == restoreAction:
model._restore_index(index)
Another alternative is to use the data() of the action, and then you either connect to the menu triggered action.
class MyTableView(QTableView):
def __init__(self, *args, **kwargs):
# ...
self._menu = QMenu(self)
self._menu.triggered.connect(self._menu_triggered)
def _menu_triggered(self, action):
if isinstance(action.data(), QtCore.QModelIndex):
self.model()._restore_index(action.data())
def _item_context_menu(self, pos):
# ...
if references in originals:
action = QAction('Restore this value', parent=self)
action.setData(index)
# ...
UPDATE: (SOLVED)
Thanks to eyllanesc for making me write a working example code of my problem. That made me find the problem. Here is a working code with a fixed problem:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
import os
class ExtendedTreeWidgetItem(QTreeWidgetItem):
def __init__(self, *args, **kwargs):
super(ExtendedTreeWidgetItem, self).__init__(*args, **kwargs)
self.rescueFile = None
print("created first time")
def setRescueFile(self, rFile):
self.rescueFile = rFile
print("setting rescue file", self.rescueFile, "for item", self.text(0))
def getRescueFile(self):
return self.rescueFile
class RescueFile:
def __init__(self, path):
self.path = path
self.ischecked = True
def isChecked(self):
return self.ischecked
def setChecked(self, checked):
if isinstance(checked, bool):
self.ischecked = checked
elif isinstance(checked, Qt.CheckState):
self.ischecked = True if checked == Qt.Checked else False
def getPath(self):
return self.path
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
windowSize = (800,400)
screenSize = QDesktopWidget().availableGeometry()
self.setGeometry(screenSize.width()/2 - windowSize[0]/2, screenSize.height()/2 - windowSize[1]//2, windowSize[0], windowSize[1])
self.setWindowTitle("TreeTest")
self.buildGui()
self.show()
def buildGui(self):
wgt = QWidget()
vlayout = QVBoxLayout()
vlayout.setAlignment(Qt.AlignTop)
grid_layout = QGridLayout()
self.setupTree(grid_layout)
vlayout.addLayout(grid_layout)
wgt.setLayout(vlayout)
self.setCentralWidget(wgt)
def setupTree(self, grid_layout):
self.treeWidget = QTreeWidget()
self.treeWidget.setHeaderLabel("Results")
self.treeWidget.setColumnCount(1)
#INSERTING DATA
topItem = ExtendedTreeWidgetItem()
topItem.setText(0, "top item")
topItem.setCheckState(0, Qt.Checked)
child1 = ExtendedTreeWidgetItem(topItem)
child1.setText(0, "child 1")
child1.setCheckState(0, Qt.Checked)
topItem.addChild(child1)
deeper_child = ExtendedTreeWidgetItem(child1)
deeper_child.setText(0, "deeper child 1")
deeper_child.setCheckState(0, Qt.Checked)
r_file = RescueFile("/home/user1/Desktop")
deeper_child.setRescueFile(r_file)
child1.addChild(deeper_child)
self.treeWidget.addTopLevelItem(topItem)
self.treeWidget.expandAll()
self.treeWidget.itemChanged.connect(self.singleClickTreeWidget)
grid_layout.addWidget(self.treeWidget, 1, 1, 4, 3)
def singleClickTreeWidget(self, widgetItem, column):
parent = widgetItem.parent()
if parent and parent.checkState(0) == Qt.Unchecked:
widgetItem.setCheckState(0, Qt.Unchecked)
return
checkState = widgetItem.checkState(0)
widgetItem.setCheckState(0, checkState)
rescue_file = widgetItem.getRescueFile()
if rescue_file:
rescue_file.setChecked(checkState)
print("rescue file found, path:", rescue_file.getPath(), "checked:", rescue_file.isChecked())
self.iterateThroughChildren(widgetItem, checkState)
def iterateThroughChildren(self, item, checkState):
for i in range(item.childCount()):
child = item.child(i)
print("child:", child, ",text:", child.text(0))
child.setCheckState(0, checkState)
# HERE WAS THE MISTAKE
# -- >> rescue_file = item.getRescueFile() << --
rescue_file = child.getRescueFile() # CORRECT CODE!!
print("rescue file", rescue_file, "child", child.text(0))
if rescue_file is not None:
rescue_file.setChecked(checkState)
else:
self.iterateThroughChildren(child, checkState)
def main():
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
app.exec_()
main()
BEFORE UPDATE:
I hope I can explain my problem clearly enough.
I trying to create QTreeWidget that uses my extended QTreeWidgetItems in python 3.5.3. Here is my code for the item class:
class ExtendedTreeWidgetItem(QTreeWidgetItem):
def __init__(self, *args, **kwargs):
super(ExtendedTreeWidgetItem, self).__init__(*args, **kwargs)
self.rescueFile = None
def setRescueFile(self, rFile):
self.rescueFile = rFile
def getRescueFile(self):
return self.rescueFile
class RescueFile:
def __init__(self, path):
self.path = path
self.ischecked = True
def isChecked(self):
return self.ischecked
def setChecked(self, checked):
if isinstance(checked, bool):
self.ischecked = checked
elif isinstance(checked, Qt.CheckState):
self.ischecked = True if checked == Qt.Checked else False
print(self.path, self.ischecked)
I use this code to implement checking and unchecking the rescue file:
****
...
self.treeWidget.itemChanged.connect(self.singleClickTreeWidget)
...
****
def singleClickTreeWidget(self, widgetItem, column):
parent = widgetItem.parent()
if parent and parent.checkState(0) == Qt.Unchecked:
widgetItem.setCheckState(0, Qt.Unchecked)
return
checkState = widgetItem.checkState(0)
widgetItem.setCheckState(0, checkState)
rescue_file = widgetItem.getRescueFile()
**# I CAN GET THE RESCUE FILE OBJECT HERE FROM**
if rescue_file:
rescue_file.setChecked(checkState)
self.iterateThroughChildren(widgetItem, checkState)
def iterateThroughChildren(self, item, checkState):
for i in range(item.childCount()):
child = item.child(i)
child.setCheckState(0, checkState)
**# I CAN'T GET ANY FIND HERE ANYMORE**
rescue_file = item.getRescueFile()
if rescue_file:
rescue_file.setChecked(checkState)
else:
self.iterateThroughChildren(child, checkState)
What my code does is that it generates a checkable tree like in the picture:
What I'm trying to achieve is that when I deselect/select an item (ExtendedTreeWidgetItem) that has children, all children are also selected/deselected as well as RescueFile objects associated with items. Only files are associated with RescueFile objects. Directories are left with self.rescueFile = None
For example if I pressed to deselect 'icons' then magnifier.png should also be deselected as well as RescueFile associated with it. Deselection of a checkboxes works like a charm but RescueFile is not affected (NOT FOUND) if I press on a parent of a file. But it works if I press directly on a file, for example magnifier.png.
I have tried to trace if it is a pointer problem but it seems like all objects point to the objects they are supposed to. I don't understand where does a rescueFile disappear if I am comming to ExtendedTreeWidgetItem recursively through it's parent.
Code:
class Example(QtGui.QWidget):
def __init__(self, parent):
super(Accounts, self).__init__()
self.initUI()
def initUI(self):
self.table = QtGui.QTableWidget()
self.table.setColumnCount(5)
database = 'Setting.db'
connection = sqlite3.connect(database)
cursor = connection.cursor()
cursor.execute('''
SELECT ID, User, Text
FROM Data ''')
data = cursor.fetchall()
num = 0
for row in data:
self.table.setRowCount(num+2)
self.table.setItem(num, 0, QtGui.QTableWidgetItem(str(row[0])))
self.table.setItem(num, 1, QtGui.QTableWidgetItem(str(row[1])))
self.table.setItem(num, 2, QtGui.QTableWidgetItem(str(row[2])))
self.table.setCellWidget(num, 3, Perms(self, row[0]))
save_user = QtGui.QPushButton("Save")
save_user.clicked.connect(self.save)
self.table.setCellWidget(num, 5, save_user)
num= num+1
main_layout = QtGui.QGridLayout()
main_layout.addWidget(self.table)
self.setLayout(main_layout)
def save(self):
button = self.sender()
index = self.table.indexAt(button.pos())
row = index.row()
a_id = str(self.table.item(row, 0).text())
data = Permissions(self, a_id).update_database()
class Perms(QtGui.QWidget):
def __init__(self, parent, a_id):
super(Perms, self).__init__()
self.a_id = a_id
self.init_ui()
def init_ui(self):
database = 'Settings.db'
conn = sqlite3.connect(database)
cursor = conn.cursor()
cursor.execute('''
SELECT control, sub
FROM Perms
WHERE ID= ?''', (self.a_id,))
row = cursor.fetchone()
control_label = QtGui.QLabel("Control")
sub_label = QtGui.QLabel("Sub")
self.control_options = QtGui.QComboBox()
self.control_options.addItem("Y")
self.control_options.addItem("N")
if str(row[0]) == "Y":
self.control_options.setCurrentIndex(0)
else:
self.control_options.setCurrentIndex(1)
self.sub_options = QtGui.QComboBox()
self.sub_options.addItem("Y")
self.sub_options.addItem("N")
if str(row[1]) == "Y":
self.sub_options.setCurrentIndex(0)
else:
self.sub_options.setCurrentIndex(1)
layout = QtGui.QGridLayout()
layout.addWidget(full_control_label, 1, 1)
layout.addWidget(self.full_control_options, 1, 2)
layout.addWidget(tills_label, 2, 1)
layout.addWidget(self.tills_options, 2, 2)
self.setLayout(layout)
def update_database(self):
control = str(self.control_options.currentText())
sub = str(self.sub_options.currentText())
return (control, sub)
Ignore any errors I don't specify because I wrote this quickly just for an example. The problem I'm facing is: the save button is created within the loop in order to be used multiple times. It connects to a function that gets the current text of the combo-boxes. But the problem is, if you change the current text in the combo-boxes and then click Save, it gets the text from the combo-boxes, but not the right text - you always get the same result.
For example:
QComboBox1: Y
QComboBox2: N
If we click Save, it'll return ('Y', 'N')
If we change the combobox values:
QComboBox1: N
QComboBox2: N
and click save, it'll return ('Y', 'N')
But it never returns the new values from the combo-boxes.
How can I fix it so I get the updated values rather than the old values?
The save method doesn't currently make much sense. Surely you need to get the Perm widget from the table, not make a new one every time:
def save(self):
button = self.sender()
index = self.table.indexAt(button.pos())
row = index.row()
# get the new values from the table
data = self.table.cellWidget(row, 3).update_database()
I want to investigate how to make a small user interface in which a user can type some letters and gets some suggestions based on a given data source (list here) which makes searches easier. For this purpose i am using Qt's QCompleter class.
In the matching elements the typed letters shall be highlighted with HTML like the example in the code below: Au<b>st</b>ria.
Finally i merged some SO answers (see How to make item view render rich (html) text in Qt) and tutorials to a small standalone module:
from PySide import QtCore, QtGui
class HTMLDelegate(QtGui.QStyledItemDelegate):
""" From: https://stackoverflow.com/a/5443112/1504082 """
def paint(self, painter, option, index):
options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)
if options.widget is None:
style = QtGui.QApplication.style()
else:
style = options.widget.style()
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(option.rect.width())
options.text = ""
style.drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
# Highlighting text if item is selected
# if options.state & QtGui.QStyle.State_Selected:
# ctx.palette.setColor(QtGui.QPalette.Text,
# options.palette.color(QtGui.QPalette.Active,
# QtGui.QPalette.HighlightedText))
textRect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText,
options)
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
doc.documentLayout().draw(painter, ctx)
painter.restore()
def sizeHint(self, option, index):
options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)
doc = QtGui.QTextDocument()
doc.setHtml(options.text)
doc.setTextWidth(options.rect.width())
return QtCore.QSize(doc.size().width(), doc.size().height())
class CustomQCompleter(QtGui.QCompleter):
""" Implement "contains" filter mode as the filter mode "contains" is not
available in Qt < 5.2
From: https://stackoverflow.com/a/7767999/1504082 """
def __init__(self, parent=None):
super(CustomQCompleter, self).__init__(parent)
self.local_completion_prefix = ""
self.source_model = None
self.delegate = HTMLDelegate()
def setModel(self, model):
self.source_model = model
super(CustomQCompleter, self).setModel(self.source_model)
def updateModel(self):
local_completion_prefix = self.local_completion_prefix
# see: http://doc.qt.io/qt-4.8/model-view-programming.html#proxy-models
class InnerProxyModel(QtGui.QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
# model index mapping by row, 1d model => column is always 0
index = self.sourceModel().index(sourceRow, 0, sourceParent)
source_data = self.sourceModel().data(index, QtCore.Qt.DisplayRole)
# performs case insensitive matching
# return True if item shall stay in th returned filtered data
# return False to reject an item
return local_completion_prefix.lower() in source_data.lower()
proxy_model = InnerProxyModel()
proxy_model.setSourceModel(self.source_model)
super(CustomQCompleter, self).setModel(proxy_model)
# #todo: Why to be set here again?
self.popup().setItemDelegate(self.delegate)
def splitPath(self, path):
self.local_completion_prefix = path
self.updateModel()
return ""
class AutoCompleteEdit(QtGui.QLineEdit):
""" Basically from:
http://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
"""
def __init__(self, list_data, separator=' ', addSpaceAfterCompleting=True):
super(AutoCompleteEdit, self).__init__()
# settings
self._separator = separator
self._addSpaceAfterCompleting = addSpaceAfterCompleting
# completer
self._completer = CustomQCompleter(self)
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.model = QtGui.QStringListModel(list_data)
self._completer.setModel(self.model)
# connect the completer to the line edit
self._completer.setWidget(self)
# trigger insertion of the selected completion when its activated
self.connect(self._completer,
QtCore.SIGNAL('activated(QString)'),
self._insertCompletion)
self._ignored_keys = [QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Tab]
def _insertCompletion(self, completion):
"""
This is the event handler for the QCompleter.activated(QString) signal,
it is called when the user selects an item in the completer popup.
It will remove the already typed string with the one of the completion.
"""
stripped_text = self.text()[:-len(self._completer.completionPrefix())]
extra_text = completion # [-extra:]
if self._addSpaceAfterCompleting:
extra_text += ' '
self.setText(stripped_text + extra_text)
def textUnderCursor(self):
text = self.text()
textUnderCursor = ''
i = self.cursorPosition() - 1
while i >= 0 and text[i] != self._separator:
textUnderCursor = text[i] + textUnderCursor
i -= 1
return textUnderCursor
def keyPressEvent(self, event):
if self._completer.popup().isVisible():
if event.key() in self._ignored_keys:
event.ignore()
return
super(AutoCompleteEdit, self).keyPressEvent(event)
completionPrefix = self.textUnderCursor()
if completionPrefix != self._completer.completionPrefix():
self._updateCompleterPopupItems(completionPrefix)
if len(event.text()) > 0 and len(completionPrefix) > 0:
self._completer.complete()
if len(completionPrefix) == 0:
self._completer.popup().hide()
def _updateCompleterPopupItems(self, completionPrefix):
"""
Filters the completer's popup items to only show items
with the given prefix.
"""
self._completer.setCompletionPrefix(completionPrefix)
# self._completer.popup().setCurrentIndex(
# self._completer.completionModel().index(0, 0))
if __name__ == '__main__':
def demo():
import sys
app = QtGui.QApplication(sys.argv)
values = ['Germany',
'Au<b>st</b>ria',
'Switzerland',
'Hungary',
'The United Kingdom of Great Britain and Northern Ireland']
editor = AutoCompleteEdit(values)
window = QtGui.QWidget()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(editor)
window.setLayout(hbox)
window.show()
sys.exit(app.exec_())
demo()
My problem is the suggestion of user Timo in the answer https://stackoverflow.com/a/5443112/1504082:
After line: 'doc.setHtml(options.text)', you need to set also doc.setTextWidth(option.rect.width()), otherwise the delegate wont render longer content correctly in respect to target drawing area. For example does not wrap words in QListView.
So i did this to avoid cropping of long text in the completer's popup. But i get the following output:
Where does this additional vertical margin come from?
I investigated this a bit and i see that the sizeHint method of HTMLDelegate is sometimes called with an options parameter which contains a rectangle with attributes (0, 0, 0, 0). And the display behaviour finally changes after the call of doc.setTextWidth(options.rect.width()). But i couldnt finally find out who calls it with this parameter and how i could properly fix this.
Can somebody explain where this comes from and how i can fix this porperly?
Finally i found another way to realize it using the idea of https://stackoverflow.com/a/8036666/1504082. Its much more forward for me without all this custom drawing things which i dont understand yet :)
from PySide import QtCore, QtGui
class TaskDelegate(QtGui.QItemDelegate):
# based on https://stackoverflow.com/a/8036666/1504082
# https://doc.qt.io/archives/qt-4.7/qitemdelegate.html#drawDisplay
# https://doc.qt.io/archives/qt-4.7/qwidget.html#render
margin_x = 5
margin_y = 3
def drawDisplay(self, painter, option, rect, text):
label = self.make_label(option, text)
# calculate render anchor point
point = rect.topLeft()
point.setX(point.x() + self.margin_x)
point.setY(point.y() + self.margin_y)
label.render(painter, point, renderFlags=QtGui.QWidget.DrawChildren)
def sizeHint(self, option, index):
# get text using model and index
text = index.model().data(index)
label = self.make_label(option, text)
return QtCore.QSize(label.width(), label.height() + self.margin_y)
def make_label(self, option, text):
label = QtGui.QLabel(text)
if option.state & QtGui.QStyle.State_Selected:
p = option.palette
p.setColor(QtGui.QPalette.WindowText,
p.color(QtGui.QPalette.Active,
QtGui.QPalette.HighlightedText)
)
label.setPalette(p)
label.setStyleSheet("border: 1px dotted black")
# adjust width according to widget's target width
label.setMinimumWidth(self.target_width - (2 * self.margin_x))
label.setMaximumWidth(self.target_width - self.margin_x)
label.setWordWrap(True)
label.adjustSize()
return label
class CustomQCompleter(QtGui.QCompleter):
""" Implement "contains" filter mode as the filter mode "contains" is not
available in Qt < 5.2
From: https://stackoverflow.com/a/7767999/1504082 """
def __init__(self, parent=None):
super(CustomQCompleter, self).__init__(parent)
self.local_completion_prefix = ""
self.source_model = None
self.delegate = TaskDelegate()
# widget not set yet
# self.delegate.target_width = self.widget().width()
def setModel(self, model):
self.source_model = model
super(CustomQCompleter, self).setModel(self.source_model)
def updateModel(self):
local_completion_prefix = self.local_completion_prefix
# see: http://doc.qt.io/qt-4.8/model-view-programming.html#proxy-models
class InnerProxyModel(QtGui.QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
# model index mapping by row, 1d model => column is always 0
index = self.sourceModel().index(sourceRow, 0, sourceParent)
source_data = self.sourceModel().data(index, QtCore.Qt.DisplayRole)
# performs case insensitive matching
# return True if item shall stay in th returned filtered data
# return False to reject an item
return local_completion_prefix.lower() in source_data.lower()
proxy_model = InnerProxyModel()
proxy_model.setSourceModel(self.source_model)
super(CustomQCompleter, self).setModel(proxy_model)
# #todo: Why to be set here again?
# -> rescale popup list items to widget width
self.delegate.target_width = self.widget().width()
self.popup().setItemDelegate(self.delegate)
def splitPath(self, path):
self.local_completion_prefix = path
self.updateModel()
return ""
class AutoCompleteEdit(QtGui.QLineEdit):
""" Basically from:
http://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
"""
def __init__(self, list_data, separator=' ', addSpaceAfterCompleting=True):
super(AutoCompleteEdit, self).__init__()
# settings
self._separator = separator
self._addSpaceAfterCompleting = addSpaceAfterCompleting
# completer
self._completer = CustomQCompleter(self)
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.model = QtGui.QStringListModel(list_data)
self._completer.setModel(self.model)
# connect the completer to the line edit
self._completer.setWidget(self)
# trigger insertion of the selected completion when its activated
self.connect(self._completer,
QtCore.SIGNAL('activated(QString)'),
self._insertCompletion)
self._ignored_keys = [QtCore.Qt.Key_Enter,
QtCore.Qt.Key_Return,
QtCore.Qt.Key_Escape,
QtCore.Qt.Key_Tab]
def _insertCompletion(self, completion):
"""
This is the event handler for the QCompleter.activated(QString) signal,
it is called when the user selects an item in the completer popup.
It will remove the already typed string with the one of the completion.
"""
stripped_text = self.text()[:-len(self._completer.completionPrefix())]
extra_text = completion # [-extra:]
if self._addSpaceAfterCompleting:
extra_text += ' '
self.setText(stripped_text + extra_text)
def textUnderCursor(self):
text = self.text()
textUnderCursor = ''
i = self.cursorPosition() - 1
while i >= 0 and text[i] != self._separator:
textUnderCursor = text[i] + textUnderCursor
i -= 1
return textUnderCursor
def keyPressEvent(self, event):
if self._completer.popup().isVisible():
if event.key() in self._ignored_keys:
event.ignore()
return
super(AutoCompleteEdit, self).keyPressEvent(event)
completionPrefix = self.textUnderCursor()
if completionPrefix != self._completer.completionPrefix():
self._updateCompleterPopupItems(completionPrefix)
if len(event.text()) > 0 and len(completionPrefix) > 0:
self._completer.complete()
if len(completionPrefix) == 0:
self._completer.popup().hide()
def _updateCompleterPopupItems(self, completionPrefix):
"""
Filters the completer's popup items to only show items
with the given prefix.
"""
self._completer.setCompletionPrefix(completionPrefix)
# self._completer.popup().setCurrentIndex(
# self._completer.completionModel().index(0, 0))
if __name__ == '__main__':
def demo():
import sys
app = QtGui.QApplication(sys.argv)
values = ['Germany',
'Au<b>st</b>ria',
'Switzerland',
'Hungary',
'The United Kingdom of Great Britain and Northern Ireland',
'USA']
editor = AutoCompleteEdit(values)
window = QtGui.QWidget()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(editor)
window.setLayout(hbox)
window.show()
sys.exit(app.exec_())
demo()