本文整理汇总了Python中PySide.QtGui.QCompleter.setModel方法的典型用法代码示例。如果您正苦于以下问题:Python QCompleter.setModel方法的具体用法?Python QCompleter.setModel怎么用?Python QCompleter.setModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PySide.QtGui.QCompleter
的用法示例。
在下文中一共展示了QCompleter.setModel方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __create_filter_ui
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
def __create_filter_ui(self):
""" Create filter widgets """
filter_layout = QHBoxLayout()
filter_layout.setSpacing(1)
filter_layout.setContentsMargins(0, 0, 0, 0)
self.filter_reset_btn = QPushButton()
icon = QIcon(':/filtersOff.png')
self.filter_reset_btn.setIcon(icon)
self.filter_reset_btn.setIconSize(QSize(22, 22))
self.filter_reset_btn.setFixedSize(24, 24)
self.filter_reset_btn.setToolTip('Reset filter')
self.filter_reset_btn.setFlat(True)
self.filter_reset_btn.clicked.connect(
partial(self.on_filter_set_text, ''))
self.filter_line = QLineEdit()
self.filter_line.setPlaceholderText('Enter filter string here')
self.filter_line.textChanged.connect(self.on_filter_change_text)
completer = QCompleter(self)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setModel(QStringListModel([], self))
self.filter_line.setCompleter(completer)
filter_layout.addWidget(self.filter_reset_btn)
filter_layout.addWidget(self.filter_line)
return filter_layout
示例2: Completer
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
class Completer(QGraphicsProxyWidget, object):
''' Class for handling text autocompletion in the SDL scene '''
def __init__(self, parent):
''' Create an autocompletion list popup '''
widget = QListWidget()
super(Completer, self).__init__(parent)
self.setWidget(widget)
self.string_list = QStringListModel()
self._completer = QCompleter()
self.parent = parent
self._completer.setCaseSensitivity(Qt.CaseInsensitive)
# For some reason the default minimum size is (61,61)
# Set it to 0 so that the size of the box is not taken
# into account when it is hidden.
self.setMinimumSize(0, 0)
self.prepareGeometryChange()
self.resize(0, 0)
self.hide()
def set_completer_list(self):
''' Set list of items for the autocompleter popup '''
compl = [item.replace('-', '_') for item in
self.parent.parentItem().completion_list]
self.string_list.setStringList(compl)
self._completer.setModel(self.string_list)
def set_completion_prefix(self, completion_prefix):
'''
Set the current completion prefix (user-entered text)
and set the corresponding list of words in the popup widget
'''
self._completer.setCompletionPrefix(completion_prefix)
self.widget().clear()
count = self._completer.completionCount()
for i in xrange(count):
self._completer.setCurrentRow(i)
self.widget().addItem(self._completer.currentCompletion())
self.prepareGeometryChange()
if count:
self.resize(self.widget().sizeHintForColumn(0) + 40, 70)
else:
self.resize(0, 0)
return count
# pylint: disable=C0103
def keyPressEvent(self, e):
super(Completer, self).keyPressEvent(e)
if e.key() == Qt.Key_Escape:
self.parentItem().setFocus()
# Consume the event so that it is not repeated at EditableText level
e.accept()
# pylint: disable=C0103
def focusOutEvent(self, event):
''' When the user leaves the popup, return focus to parent '''
super(Completer, self).focusOutEvent(event)
self.hide()
self.resize(0, 0)
self.parentItem().setFocus()
示例3: config_completer
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
def config_completer(line_edit, model, field):
# sets up a completer based on a QSqlTableModel for the specified field on a QLineEdit
completer = QCompleter()
completer.setModel(model)
completer.setCompletionColumn(model.fieldIndex(field))
completer.setCompletionMode(QCompleter.PopupCompletion)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.activated.connect(line_edit.returnPressed)
line_edit.setCompleter(completer)
示例4: createEditor
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
def createEditor(self, parent, option, index):
""" Should return a LineEdit with all the Category Names as AutoComplete values """
edit = QLineEdit(parent)
completer = QCompleter()
edit.setCompleter(completer)
model = QStringListModel()
completer.setModel(model)
self.setCompleterData(model)
return edit
示例5: TagEdit
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
class TagEdit(object):
"""Abstraction for tag edit"""
def __init__(self, parent, widget, on_change):
"""Init and connect signals"""
self.parent = parent
self.app = QApplication.instance()
self.widget = widget
self.tags_list = map(lambda tag:
Tag.from_tuple(tag).name,
self.app.provider.list_tags(),
)
self.completer = QCompleter()
self.completer_model = QStringListModel()
self.completer.setModel(self.completer_model)
self.completer.activated.connect(self.update_completion)
self.update_completion()
self.widget.setCompleter(self.completer)
self.widget.textChanged.connect(Slot()(on_change))
self.widget.textEdited.connect(self.update_completion)
@property
def tags(self):
"""Get tags"""
# Split on comma and Arabic comma
# 0x060c is the Arabic comma
return map(lambda tag: tag.strip(),
re.split(u',|\u060c', self.widget.text()))
@tags.setter
def tags(self, val):
"""Set tags"""
self.widget.setText(', '.join(val))
@Slot()
def update_completion(self):
"""Update completion model with exist tags"""
orig_text = self.widget.text()
text = ', '.join(orig_text.replace(', ', ',').split(',')[:-1])
tags = []
for tag in self.tags_list:
if ',' in orig_text:
if orig_text[-1] not in (',', ' '):
tags.append('%s,%s' % (text, tag))
tags.append('%s, %s' % (text, tag))
else:
tags.append(tag)
if tags != self.completer_model.stringList():
self.completer_model.setStringList(tags)
示例6: _createApiChooserLineedit
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
def _createApiChooserLineedit(self):
"""
Create the I{QLineEdit }used for selecting API names. This includes a QCompleter to make suggestions based on
the keyword database.
"""
self.api_chooser_lineedit = QLineEdit()
self.api_chooser_lineedit.returnPressed.connect(self.populateBrowserWindow)
self.api_chooser_lineedit.textChanged.connect(self._updateCompleterModel)
completer = QCompleter()
completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
completer.setModelSorting(QCompleter.CaseSensitivelySortedModel)
self.completer_model = QStringListModel([])
completer.setModel(self.completer_model)
self.api_chooser_lineedit.setCompleter(completer)
示例7: TagEdit
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
class TagEdit(object):
"""Abstraction for tag edit"""
def __init__(self, parent, app, widget, on_change):
"""Init and connect signals"""
self.parent = parent
self.app = app
self.widget = widget
self.tags_list = map(lambda tag: Tag.from_tuple(tag).name, self.app.provider.list_tags())
self.completer = QCompleter()
self.completer_model = QStringListModel()
self.completer.setModel(self.completer_model)
self.completer.activated.connect(self.update_completion)
self.update_completion()
self.widget.setCompleter(self.completer)
self.widget.textChanged.connect(Slot()(on_change))
self.widget.textEdited.connect(self.update_completion)
@property
def tags(self):
"""Get tags"""
return map(lambda tag: tag.strip(), self.widget.text().split(","))
@tags.setter
def tags(self, val):
"""Set tags"""
self.widget.setText(", ".join(val))
@Slot()
def update_completion(self):
"""Update completion model with exist tags"""
orig_text = self.widget.text()
text = ", ".join(orig_text.replace(", ", ",").split(",")[:-1])
tags = []
for tag in self.tags_list:
if "," in orig_text:
if orig_text[-1] not in (",", " "):
tags.append("%s,%s" % (text, tag))
tags.append("%s, %s" % (text, tag))
else:
tags.append(tag)
if tags != self.completer_model.stringList():
self.completer_model.setStringList(tags)
示例8: CodeCompletionMode
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
#.........这里部分代码省略.........
"""
self.__completer.popup().hide()
QToolTip.hideText()
def _requestCompletion(self, completionPrefix, onlyAdapt=False):
"""
Requests a code completion. The request will be transmitted to the
background thread and treated by the __applyRequestResults slot when
__completionResultsAvailable is emitted.
:param completionPrefix:
:param onlyAdapt:
:return:
"""
# cancel prev running request
if not onlyAdapt:
request = self._getCCRequest(completionPrefix)
else:
request = CompletionRequest(completionPrefix=completionPrefix,
onlyAdapt=True)
# only one at a time
if self.__active_thread_count == 0:
if self.__cached_request:
self.__cached_request, request = request, self.__cached_request
self.__active_thread_count += 1
runnable = RunnableCompleter(self._models, request)
runnable.connect(self._applyRequestResults)
self.thread_pool.start(runnable)
# cache last request
else:
self.__cached_request = request
def _applyRequestResults(self, request):
"""
Updates the completer model and show the popup
"""
self.__active_thread_count -= 1
# is the request still up to date ?
if request.completionPrefix == self._textUnderCursor():
if not request.onlyAdapt:
# update completion model and show completer
cc_model, cptSuggestion = self._createCompleterModel(
request.completionPrefix)
if cptSuggestion > 1:
self.__completer.setModel(cc_model)
self.__cc_model = cc_model
self._showCompletions(request.completionPrefix)
else:
self._hideCompletions()
else:
# only adapt completion prefix, the completer is already visible
self.__completer.setCompletionPrefix(request.completionPrefix)
idx = self.__completer.completionModel().index(0, 0)
self.__completer.popup().setCurrentIndex(idx)
if self.__completer.currentCompletion() == "" or \
self.__completer.currentCompletion() == \
request.completionPrefix:
self._hideCompletions()
# do we have any cached requests?
if self.__cached_request and self.__active_thread_count == 0:
self.__active_thread_count += 1 # prevent normal start immediately
self.__timer.singleShot(10, self.__start_cached_request)
def __start_cached_request(self):
request = self.__cached_request
self.__cached_request = None
runnable = RunnableCompleter(self._models, request)
runnable.connect(self._applyRequestResults)
self.thread_pool.start(runnable)
@Slot(unicode)
def _displayHighlightedTooltip(self, txt):
"""
Shows/hides current suggestion tooltip next to the completer popup
:param txt:
:return:
"""
if not self.displayTooltips or not txt in self.__tooltips:
QToolTip.hideText()
return
tooltip = self.__tooltips[txt]
charWidth = self.editor.codeEdit.fm.width('A')
# show tooltip
pos = self.__completer.popup().pos()
pos.setX(pos.x() + 400)
pos.setY(pos.y() - 15)
QToolTip.showText(pos, tooltip, self.editor.codeEdit)
def _insertCompletion(self, completion):
"""
Inserts the completion (replace the word under cursor)
:param completion: the completion text to insert
"""
offset = 0
if len(self._textUnderCursor()) > 1:
offset = 1
tc = self.selectWordUnderCursor()
tc.insertText(completion)
self.editor.codeEdit.setTextCursor(tc)
示例9: __init__
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
def __init__(self, model, index, parent=None):
super(ObservationDialog, self).__init__(parent)
self.logger = Logger('root.observationDialog')
self.logger.debug('Debug set to: %s' % str(parent.logger.debugging))
self.setupUi(self)
# self.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
# An observation model is passed to the constructor as a parameter
self.model = model
# Build a QCompleter that is based on a species model's species name.
# This way user can start typing the name in a line edit and the
# completion will suggest suitable species names based on the model
# TODO: language for the species name completion needs to be handled
# TODO: both completers have model column indexes hard coded in, thus
# they will break if the model is modified
sppCompleter = QCompleter(self)
sppCompleter.setModel(self.model.data_model)
sppCompleter.setCompletionColumn(4)
sppCompleter.setCompletionMode(QCompleter.InlineCompletion)
sppCompleter.setCaseSensitivity(Qt.CaseInsensitive)
self.sppLineEdit.setCompleter(sppCompleter)
# Build a QCompleter that is based on a species model's abbreviation.
# This way user can start typing the abbreviation in a line edit and the
# completion will suggest suitable species names based on the model
abbrCompleter = QCompleter(self)
abbrCompleter.setModel(self.model.data_model)
abbrCompleter.setCompletionColumn(1)
abbrCompleter.setCompletionMode(QCompleter.InlineCompletion)
self.abbrLineEdit.setCompleter(abbrCompleter)
# The underlying (observation) model is automatically updated through
# a QDataWidgetMapper
self.mapper = QDataWidgetMapper(self)
self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
self.mapper.setModel(model)
# ID is mapped to a disabled dummy label in order to include it in the
# WidgetMapper --> not very elegant
self.mapper.addMapping(self.idLineEdit, model.ID)
self.mapper.addMapping(self.sppLineEdit, model.SPECIES)
self.mapper.addMapping(self.abbrLineEdit, model.ABBR)
self.mapper.addMapping(self.countSpinBox, model.COUNT)
self.mapper.addMapping(self.dateTimeEdit, model.TIME)
self.mapper.addMapping(self.locLineEdit, model.LOCATION)
self.mapper.addMapping(self.notesTextEdit, model.NOTES)
self.mapper.setCurrentModelIndex(index)
self.firstButton.clicked.connect(
lambda: self.saveRecord(ObservationDialog.FIRST))
self.prevButton.clicked.connect(
lambda: self.saveRecord(ObservationDialog.PREV))
self.nextButton.clicked.connect(
lambda: self.saveRecord(ObservationDialog.NEXT))
self.lastButton.clicked.connect(
lambda: self.saveRecord(ObservationDialog.LAST))
self.saveButton.clicked.connect(
lambda: self.saveRecord(ObservationDialog.CURRENT))
self.closeButton.clicked.connect(self.reject)
self.sppLineEdit.editingFinished.connect(self.update_fields)
示例10: mainwin
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
#.........这里部分代码省略.........
#connections
self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search)
self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent)
self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter)
self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
def writehistlis(self, lis):
if len(lis) >= 2:
for i in range(1, len(lis)):
cur.execute("insert into HISTORY values(?)", (lis[i], ))
def writebkmlis(self, lis):
cur.execute("delete from BOOKMARKS")
if len(lis) > 0:
for i in range(len(lis)):
cur.execute("insert into BOOKMARKS values(?)", (lis[i], ))
def listwidcall(self, item):
self.comboBox.setText(item.text())
self.setevent()
def search(self, text, *args):
li = []
tplus = text + "%"
cur.execute("select ENGW from ENGTAM where ENGW like ? limit 20", (tplus, ))
cuf = cur.fetchall()
model = QStringListModel()
for i in range(len(cuf)):
k = cuf[i][0]
li.append(k)
model.setStringList(li)
self.completer.setModel(model)
def returnpressedevent(self, *args):
self.comboBox.selectAll()
self.returncount += 1
if self.returncount % 2 == 0:
self.setevent()
else:
self.comboBox.selectAll()
def setevent(self):
self.comboBox.selectAll()
self.bkm_addfav.setEnabled(True)
lis = []
eng = self.comboBox.text()
cur.execute("SELECT rowid, TAMW FROM ENGTAM WHERE ENGW like ? limit 1", (eng,))
cuf = cur.fetchall()
if len(cuf) == 0:
self.tamtext.setText("No words found. . . ")
self.listview.addItem("No Suggestions. . .")
else:
for i in range(len(cuf)):
tam = cuf[0][1]
rowid = cuf[0][0]
self.tamtext.setText(tam)
if rowid <= 25:
start = 0
end = 50
elif rowid >= 190513:
start = rowid - 190487
end = rowid + 190537
else:
start = rowid - 25
示例11: EditorCodeCompletion
# 需要导入模块: from PySide.QtGui import QCompleter [as 别名]
# 或者: from PySide.QtGui.QCompleter import setModel [as 别名]
class EditorCodeCompletion(QTextEdit):
def __init__(self, path_dict):
super(EditorCodeCompletion, self).__init__()
self.m_completer = QCompleter(self)
self.m_completer.setWidget(self)
words = []
self.flag_open_angle_bracket = False
self.tag_name = ""
try:
f = open(path_dict,"r")
for word in f:
words.append(word.strip())
f.close()
except IOError:
print ("dictionary not in anticipated location")
model = QStringListModel(words, self.m_completer)
self.m_completer.setModel(model)
self.m_completer.setCompletionMode(QCompleter.PopupCompletion)
self.m_completer.activated.connect(self.insertCompletion)
def insertCompletion (self, completion):
cursor = self.textCursor()
cursor.beginEditBlock()
cursor.movePosition(QTextCursor.Left)
cursor.movePosition(QTextCursor.EndOfWord)
extra = len(self.m_completer.completionPrefix())
cursor.insertText(completion[extra:])
self.setTextCursor(cursor)
cursor.endEditBlock()
def __insertTag(self):
'''
inserts the corresponding closing tag to an opening xml tag
'''
self.find('<', QTextDocument.FindBackward)
tc = self.textCursor()
tc.select(QTextCursor.WordUnderCursor)
txt = '' if self.__stringHasBracket(tc.selectedText().replace(' ', '')) else tc.selectedText()
txt = '</' + txt + '>'
self.find('>')
tc = self.textCursor()
tc.clearSelection()
tc.insertText(txt)
tc.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, len(txt))
self.setTextCursor(tc)
def __stringHasBracket(self, s):
return '<' in s or '>' in s
def __insertClosingTag(self, event):
operation_sys = sys.platform
flag = "linux" in operation_sys
if flag :
self.__insertClosingTag_Unix(event)
else:
self.__insertClosingTag_Win(event)
def __insertClosingTag_Unix(self, event):
'''
inserts a closing tag after the closing bracket of open tag
@param key: keyboard input value as int
'''
if self.flag_open_angle_bracket :
if event.key() == 47 : # /
print ("/")
self.flag_open_angle_bracket = False
elif event.key() == 62 : # >
print (">")
self.__insertTag()
self.flag_open_angle_bracket = False
elif event.key() == 60 : # <
print ("<")
self.flag_open_angle_bracket = True
def __insertClosingTag_Win(self, event) :
if self.flag_open_angle_bracket :
if event.modifiers() & Qt.ShiftModifier :
if event.key() == 55 : # /
print ("/")
self.flag_open_angle_bracket = False
elif event.key() == 60 : # >
print (">")
self.__insertTag()
self.flag_open_angle_bracket = False
elif event.key() == 60 : # <
print ("<")
self.flag_open_angle_bracket = True
def keyPressEvent(self, event):
'''
checks keyboard input to set closing tag or start code completion
'''
if self.m_completer.popup().isVisible() :
if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return or event.key() == Qt.Key_Tab or event.key() == Qt.Key_Escape :
#.........这里部分代码省略.........