Making QCompleter complete every word [duplicate] - python

I want to have the possibility to use multiple times the auto completer in my QLineEdit, I found example using QTextEdit but I can't find for QLineEdit. here is a piece of code I use (very simple one) :
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
def main():
app = QApplication(sys.argv)
edit = QLineEdit()
strList = ["Germany", "Spain", "France", "Norway"]
completer = QCompleter(strList,edit)
edit.setCompleter(completer)
edit.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
For example, I want the completer to "start predicting" again the words in the same QLineEdit if I add a comma.
Thanks.

I've found the answer if it can help others, I created a class for Completer :
class Completer(QtWidgets.QCompleter):
def __init__(self, parent=None):
super(Completer, self).__init__(parent)
self.setCaseSensitivity(Qt.CaseInsensitive)
self.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
self.setWrapAround(False)
# Add texts instead of replace
def pathFromIndex(self, index):
path = QtWidgets.QCompleter.pathFromIndex(self, index)
lst = str(self.widget().text()).split(',')
if len(lst) > 1:
path = '%s, %s' % (','.join(lst[:-1]), path)
return path
# Add operator to separate between texts
def splitPath(self, path):
path = str(path.split(',')[-1]).lstrip(' ')
return [path]
And I use it within a class for QLineEdit like :
class TextEdit(QtWidgets.QLineEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
self.setPlaceholderText("example : ")
self._completer = Completer(self)
self.setCompleter(self._completer)

Solution for PyQt4:
from PyQt4 import QtCore, QtGui
class Completer(QtGui.QCompleter):
def __init__(self, *args, **kwargs):
super(Completer, self).__init__(*args, **kwargs)
self.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.setWrapAround(False)
# Add texts instead of replace
def pathFromIndex(self, index):
path = QtGui.QCompleter.pathFromIndex(self, index)
lst = str(self.widget().text()).split(',')
if len(lst) > 1:
path = '%s, %s' % (','.join(lst[:-1]), path)
return path
def splitPath(self, path):
path = str(path.split(',')[-1]).lstrip(' ')
return [path]
class TextEdit(QtGui.QLineEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
words = ["alpha", "omega", "omicron", "zeta"]
self.setPlaceholderText("example : ")
self._completer = Completer(words, self)
self.setCompleter(self._completer)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = TextEdit()
w.show()
sys.exit(app.exec_())

Here is what I found might be helpful to someone:
class LineEdit(QLineEdit):
def __init__(self, *args, **kwargs):
super(LineEdit,self).__init__( *args, **kwargs)
self.multipleCompleter = None
def keyPressEvent(self, event):
QLineEdit.keyPressEvent(self, event)
if not self.multipleCompleter:
return
c = self.multipleCompleter
if self.text() == "":
return
c.setCompletionPrefix(self.cursorWord(self.text()))
if len(c.completionPrefix()) < 1:
c.popup().hide()
return
c.complete()
def cursorWord(self, sentence):
p = sentence.rfind(" ")
if p == -1:
return sentence
return sentence[p + 1:]
def insertCompletion(self, text):
p = self.text().rfind(" ")
if p == -1:
self.setText(text)
else:
self.setText(self.text()[:p+1]+ text)
def setMultipleCompleter(self, completer):
self.multipleCompleter = completer
self.multipleCompleter.setWidget(self)
completer.activated.connect(self.insertCompletion)
def main():
app = QApplication(sys.argv)
w = LineEdit()
completer = QCompleter(["Animals", "Dogs", "Birds", "Cats", "Elephant", "Zebra"])
completer.setCaseSensitivity(Qt.CaseInsensitive)
w.setMultipleCompleter(completer)
w.show()
sys.exit(app.exec_())

Related

Using qHelpEngine

I want to make a help file using QtHelp and QHelpEngine. I currently have some code but I am not sure about my errors and the documentation is a little vague in my opinion. Nonetheless the current issue I am facing is one of connecting signal and slots. The error I currently get is AttributeError: 'builtin_function_or_method' object has no attribute 'linkActivated' Not sure the reason for this as the documentation states that contentWidget does have a signal called linkActivated. And an error occurs here textViewer = QtWidgets.QTextBrowser(helpEngine)
Reference
from PyQt5 import QtCore, QtGui, QtWidgets, QtHelp
import os
class Ui_HelpSetupClass(QtWidgets.QDockWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
def setupUi(self, HelpSetupClass):
qUrl = "qthelp://ut.tool.help/tool/index.html"
HELP_DIR = os.getcwd()
HELP_PATH = HELP_DIR + "\\" + "Help" + "\\" + "help_file.qhc"
helpEngine = QtHelp.QHelpEngine(HELP_PATH)
helpEngine.setupData()
tableWidget = QtWidgets.QTabWidget()
tableWidget.setMaximumWidth(200)
tableWidget.addTab(helpEngine.contentWidget(), "Contents")
tableWidget.addTab(helpEngine.indexWidget(), "Index")
textViewer = QtWidgets.QTextBrowser(helpEngine)
textViewer.setSource(qUrl)
helpEngine.contentWidget.linkActivated(qUrl ).connect(textViewer.setSource(qUrl))
helpEngine.indexWidget.documentActivated(qUrl ).connect(textViewer.setSource(qUrl))
horizSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
horizSplitter.insertWidget(0, tableWidget)
horizSplitter.insertWidget(1, textViewer)
horizSplitter.hide()
helpWindow = QtWidgets.QDockWidget("Help", self)
helpWindow.setWidget(horizSplitter)
helpWindow.hide()
QtWidgets.QMainWindow.addDockWidget(QtCore.Qt.BottomDockWidgetArea, helpWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_HelpSetupClass()
ui.show()
sys.exit(app.exec_())
In your translation of the C++ code to Python it shows many errors so I will avoid pointing it out and I will only show the correct translation:
import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtHelp
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class HelpBrowser(QtWidgets.QTextBrowser):
def __init__(self, helpEngine, parent=None):
super().__init__(parent)
self.helpEngine = helpEngine
def loadResource(self, _type, name):
if name.scheme() == "qthelp":
return self.helpEngine.fileData(name)
else:
return super().loadResource(_type, name)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.scene = QtWidgets.QGraphicsScene()
self.scene.setSceneRect(0, 0, 400, 200)
self.view = QtWidgets.QGraphicsView(self.scene)
self.view.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
self.view.setRenderHints(QtGui.QPainter.Antialiasing)
self.setCentralWidget(self.view)
self.createHelpWindow()
self.createActions()
self.createMenus()
self.createConnections()
self.setWindowTitle(self.tr("QGraphicsScene Help Example"))
self.resize(640, 480)
def createHelpWindow(self):
self.helpEngine = QtHelp.QHelpEngine(
os.path.join(CURRENT_DIR, "documentation", "qgraphicshelpexample.qhc")
)
self.helpEngine.setupData()
tWidget = QtWidgets.QTabWidget()
tWidget.setMaximumWidth(200)
tWidget.addTab(self.helpEngine.contentWidget(), "Contents")
tWidget.addTab(self.helpEngine.indexWidget(), "Index")
textViewer = HelpBrowser(self.helpEngine)
textViewer.setSource(
QtCore.QUrl("qthelp://walletfox.qt.helpexample/doc/index.html")
)
self.helpEngine.setUsesFilterEngine(True)
self.helpEngine.contentWidget().linkActivated.connect(textViewer.setSource)
self.helpEngine.indexWidget().linkActivated.connect(textViewer.setSource)
horizSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
horizSplitter.insertWidget(0, tWidget)
horizSplitter.insertWidget(1, textViewer)
horizSplitter.hide()
self.helpWindow = QtWidgets.QDockWidget(self.tr("Help"), self)
self.helpWindow.setWidget(horizSplitter)
self.helpWindow.hide()
self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.helpWindow)
def createActions(self):
self.insertEllipseAction = QtWidgets.QAction(self.tr("Insert &Ellipse"), self)
self.insertEllipseAction.setIcon(QtGui.QIcon(":/icons/ellipse.png"))
self.insertRectangleAction = QtWidgets.QAction(
self.tr("Insert &Rectangle"), self
)
self.insertRectangleAction.setIcon(QtGui.QIcon(":/icons/rectangle.png"))
self.helpAction = QtWidgets.QAction(self.tr("Help Contents..."), self)
self.helpAction.setShortcut(QtGui.QKeySequence.HelpContents)
self.aboutAction = QtWidgets.QAction(self.tr("&About"), self)
def createMenus(self):
self.itemMenu = QtWidgets.QMenu(self.tr("&Item"), self)
self.itemMenu.addAction(self.insertEllipseAction)
self.itemMenu.addAction(self.insertRectangleAction)
self.helpMenu = QtWidgets.QMenu(self.tr("&Help"), self)
self.helpMenu.addAction(self.helpAction)
self.helpMenu.addAction(self.aboutAction)
self.menuBar().addMenu(self.itemMenu)
self.menuBar().addMenu(self.helpMenu)
def insertItem(self):
action = self.sender()
if isinstance(action, QtWidgets.QAction):
itemToAdd = None
mPen = QtGui.QPen(QtCore.Qt.black, 3, QtCore.Qt.SolidLine)
eBrush = QtGui.QBrush(QtGui.QColor("#FF7F50"))
rBrush = QtGui.QBrush(QtGui.QColor("#CC0000"))
if action.iconText() == "Insert Ellipse":
itemToAdd = self.scene.addEllipse(0, 0, 150, 75, mPen, eBrush)
elif action.iconText() == "Insert Rectangle":
itemToAdd = self.scene.addRect(0, 0, 100, 100, mPen, rBrush)
if itemToAdd is not None:
itemToAdd.setFlags(
QtWidgets.QGraphicsItem.ItemIsSelectable
| QtWidgets.QGraphicsItem.ItemIsMovable
)
def about(self):
QtWidgets.QMessageBox.about(
self,
self.tr("About QGraphicsScene Help Example"),
self.tr(
"This example demonstrates how to implement\n"
"help for a Qt application."
),
)
def createConnections(self):
self.insertEllipseAction.triggered.connect(self.insertItem)
self.insertRectangleAction.triggered.connect(self.insertItem)
self.helpAction.triggered.connect(self.helpWindow.show)
self.aboutAction.triggered.connect(self.about)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_A:
for item in self.scene.selectedItems():
self.scene.removeItem(item)
else:
super().keyPressEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Note: Using the original file "qgraphicshelpexample.qhp" causes me errors since the "./foo" paths like "./insertobject.html" are not resolved correctly so I change them to "foo".
The complete example can be found here.

Change color in qtablewidget (click on)

Help implement the code so that when you click on a cell in the table, the widget cell changes its color, and when you click it again, it turns white again
I'm trying to implement the filemanager.
Code:
def onClicked(self, cell):
if not self.highlight_mode:
print(cell)
if cell.text() == '..':
self.path = str(Path(self.path).parent)
print(self.path)
else:
if not os.path.isfile(self.path + "\\" + str(cell.text())):
self.path = self.path + "\\" + str(cell.text())
print(self.path)
try:
os.chdir(self.path)
self.list_dir = os.listdir(self.path)
self.list_dir.insert(0, '..')
except:
buttonReply = QMessageBox.question(self, 'ERROR', "ERROR",
QMessageBox.Ok, QMessageBox.Ok)
self.update_table()
else:
if cell.text() != '..':
self.list_with_select.append(self.path + '\\' + str(cell.text()))
print(self.list_with_select)
def update_table(self):
self.tableWidget.clear()
self.tableWidget.setRowCount(len(self.list_dir))
self.tableWidget.setColumnCount(1)
count = 0
for nel in self.list_dir:
self.tableWidget.setItem(0, count, QTableWidgetItem(nel))
count += 1
def cut(self):
for i in self.list_with_select:
shutil.move(i, self.path + '\\')
self.list_with_select.clear()
def highlight_m(self):
print('recup')
if not(self.highlight_mode):
self.highlight_mode = True
else:
self.highlight_mode = False
print(self.highlight_mode)
You must toggle the QBrush associated with the Qt::BackgroundRole function of each element. You can use itemClicked but this may fail because not all items in QTableWidget have an associated QTableWidgetItem, so it is better to use the clicked signal returned by the associated QModelIndex
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.tableWidget = QtWidgets.QTableWidget()
self.setCentralWidget(self.tableWidget)
self.tableWidget.clicked.connect(self.on_clicked)
self.tableWidget.setRowCount(10)
self.tableWidget.setColumnCount(4)
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_clicked(self, ix):
alternative_color = QtGui.QColor("salmon")
current_brush = ix.data(QtCore.Qt.BackgroundRole)
new_brush = (
QtGui.QBrush(alternative_color)
if current_brush in (None, QtGui.QBrush())
else QtGui.QBrush()
)
self.tableWidget.model().setData(ix, new_brush, QtCore.Qt.BackgroundRole)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Customize QCompleter with QSortFilterProxyModel

I want to enable wildcard matching for QLineEdit and QCompleter. If the string model is ['abc', 'cba'], when I type ab* or a*, it should display abc. Below is the code I wrote, but it still behaves like a regular match. Any idea how I should fix it?
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys, random
class MyCompleter(QCompleter):
def __init__(self, *args):
super().__init__(*args)
def setModel(self, model):
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setSourceModel(model)
super().setModel(self.proxyModel)
def updatePattern(self, patternStr):
self.proxyModel.setFilterWildcard(patternStr)
class MyMain(QMainWindow):
def __init__(self, *args):
super().__init__(*args)
self.initUI()
def initUI(self):
model = QStringListModel(['abc', 'cba'])
completer = MyCompleter()
completer.setModel(model)
searchBar = QLineEdit(self)
searchBar.setCompleter(completer)
searchBar.textChanged.connect(lambda wildcard: completer.updatePattern(wildcard))
vLayout = QVBoxLayout()
vLayout.addWidget(searchBar, alignment=Qt.AlignCenter)
self.setCentralWidget(QWidget())
self.centralWidget().setLayout(vLayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
mm = MyMain()
mm.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class LineEdit(QLineEdit): # +++
def __init__(self, *args, **kwargs):
QLineEdit.__init__(self, *args, **kwargs)
self.multipleCompleter = None
def keyPressEvent(self, event):
QLineEdit.keyPressEvent(self, event)
if not self.multipleCompleter:
return
c = self.multipleCompleter
if self.text() == "":
return
c.setCompletionPrefix(self.cursorWord(self.text()))
if len(c.completionPrefix()) < 1:
c.popup().hide()
return
c.complete()
def cursorWord(self, sentence):
p = sentence.rfind(" ")
if p == -1:
return sentence
return sentence[p + 1:]
def insertCompletion(self, text):
p = self.text().rfind(" ")
if p == -1:
self.setText(text)
else:
self.setText(self.text()[:p+1]+ text)
def setMultipleCompleter(self, completer):
self.multipleCompleter = completer
self.multipleCompleter.setWidget(self)
completer.activated.connect(self.insertCompletion)
class MyCompleter(QCompleter):
def __init__(self, *args):
super().__init__(*args)
def setModel(self, model):
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setSourceModel(model)
super().setModel(self.proxyModel)
def updatePattern(self, patternStr):
print(f"patternStr-> {patternStr}")
self.proxyModel.setFilterWildcard(patternStr)
class MyMain(QMainWindow):
def __init__(self, *args):
super().__init__(*args)
self.initUI()
def initUI(self):
model = QStringListModel(['abc', 'cba'])
completer = MyCompleter()
completer.setModel(model)
# searchBar = QLineEdit(self)
# searchBar.setCompleter(completer)
# searchBar.textChanged.connect(lambda wildcard: completer.updatePattern(wildcard))
searchBar = LineEdit(self) # +++
completer.setCaseSensitivity(Qt.CaseInsensitive) # +++
searchBar.setMultipleCompleter(completer) # +++
vLayout = QVBoxLayout()
vLayout.addWidget(searchBar, alignment=Qt.AlignCenter)
self.setCentralWidget(QWidget())
self.centralWidget().setLayout(vLayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
mm = MyMain()
mm.show()
sys.exit(app.exec_())

PyQt4 : making certain text on QTextEdit uneditable

Is there any way I can make certain text on QTextEdit permanent. Applications like cmd.exe where the current user directory is displayed and the rest of the screen is up for input. I tried inserting a QLabel but unable to do so, here's my code, I am currently taking user input through a separate line edit.
UPDATE I had a look at Ipython QtConsole where the line number is displayed constantly, how can I do that, I am looking in the source but if anyone who already knows it, please do tell. Here is the QtConsole for ipython notebook, I am trying to replicate this.
import os
import sys
import PyQt4
import PyQt4.QtCore
from PyQt4.QtGui import *
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
# create objects
label = QLabel(self.tr("Enter command and press Return"))
self.le = QLineEdit()
self.te = QTextEdit()
self.lbl = QLabel(str(os.getcwd())+"> ")
# layout
layout = QVBoxLayout(self)
layout.addWidget(label)
layout.addWidget(self.le)
layout.addWidget(self.te)
self.setLayout(layout)
# styling
self.te.setReadOnly(True)
# create connection
self.mytext = str(self.le.text())
self.connect(self.le, PyQt4.QtCore.SIGNAL("returnPressed(void)"),
self.display)
def display(self):
mytext = str(self.le.text())
self.te.append(self.lbl +str(os.popen(mytext).read()))
self.le.setText("")
if __name__ == "__main__":
main()
A simple solution is to create a class that inherits from QTextEdit and overwrite and add the necessary attributes as shown below:
class TextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.staticText = os.getcwd()
self.counter = 1
self.setReadOnly(True)
def append(self, text):
n_text = "{text} [{number}] > ".format(text=self.staticText, number=self.counter)
self.counter += 1
QTextEdit.append(self, n_text+text)
Complete Code:
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.staticText = os.getcwd()
self.counter = 1
self.setReadOnly(True)
def append(self, text):
n_text = "{text} [{number}] > ".format(text=self.staticText, number=self.counter)
self.counter += 1
QTextEdit.append(self, n_text+text)
class MyWindow(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
label = QLabel(self.tr("Enter command and press Return"), self)
self.le = QLineEdit(self)
self.te = TextEdit(self)
# layout
layout = QVBoxLayout(self)
layout.addWidget(label)
layout.addWidget(self.le)
layout.addWidget(self.te)
self.setLayout(layout)
self.connect(self.le, SIGNAL("returnPressed(void)"), self.display)
# self.le.returnPressed.connect(self.display)
def display(self):
command = str(self.le.text())
resp = str(os.popen(command).read())
self.te.append(resp)
self.le.clear()
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
To emulate QtConsole we must overwrite some methods of QTextEdit, catch some events, and verify that it does not eliminate the prefix as I show below:
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.staticText = os.getcwd()
self.counter = 1
self.prefix = ""
self.callPrefix()
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.onCustomContextMenuRequest)
def onCustomContextMenuRequest(self, point):
menu = self.createStandardContextMenu()
for action in menu.actions():
if "Delete" in action.text():
action.triggered.disconnect()
menu.removeAction(action)
elif "Cu&t" in action.text():
action.triggered.disconnect()
menu.removeAction(action)
elif "Paste" in action.text():
action.triggered.disconnect()
act = menu.exec_(point)
if act:
if "Paste" in act.text():
self.customPaste()
def customPaste(self):
self.moveCursor(QTextCursor.End)
self.insertPlainText(QApplication.clipboard().text())
self.moveCursor(QTextCursor.End)
def clearCurrentLine(self):
cs = self.textCursor()
cs.movePosition(QTextCursor.StartOfLine)
cs.movePosition(QTextCursor.EndOfLine)
cs.select(QTextCursor.LineUnderCursor)
text = cs.removeSelectedText()
def isPrefix(self, text):
return self.prefix == text
def getCurrentLine(self):
cs = self.textCursor()
cs.movePosition(QTextCursor.StartOfLine)
cs.movePosition(QTextCursor.EndOfLine)
cs.select(QTextCursor.LineUnderCursor)
text = cs.selectedText()
return text
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
command = self.getCurrentLine()[len(self.prefix):]
self.execute(command)
self.callPrefix()
return
elif event.key() == Qt.Key_Backspace:
if self.prefix == self.getCurrentLine():
return
elif event.matches(QKeySequence.Delete):
return
if event.matches(QKeySequence.Paste):
self.customPaste()
return
elif self.textCursor().hasSelection():
t = self.toPlainText()
self.textCursor().clearSelection()
QTextEdit.keyPressEvent(self, event)
self.setPlainText(t)
self.moveCursor(QTextCursor.End)
return
QTextEdit.keyPressEvent(self, event)
def callPrefix(self):
self.prefix = "{text} [{number}] >".format(text=self.staticText, number=self.counter)
self.counter += 1
self.append(self.prefix)
def execute(self, command):
resp = os.popen(command).read()
self.append(resp)
class MyWindow(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
label = QLabel(self.tr("Enter command and press Return"), self)
self.te = TextEdit(self)
# layout
layout = QVBoxLayout(self)
layout.addWidget(label)
layout.addWidget(self.te)
self.setLayout(layout)
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

How to get QComboBox Item data

Instead of using .addItem("Item Name", "My Data") to populate the QComboBox
I create its item first:
item = QtGui.QStandardItem("Item Name")
Then I set item's data:
item.setData("My data")
Question. How to get the data stored in Combo's Item from inside of currentIndexChanged() method which gets the clicked ComboBox item's index as an argument:
import sys
import PySide.QtCore as QtCore
import PySide.QtGui as QtGui
class MyCombo(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
vLayout=QtGui.QVBoxLayout(self)
self.setLayout(vLayout)
self.combo=QtGui.QComboBox(self)
self.combo.currentIndexChanged.connect(self.currentIndexChanged)
comboModel=self.combo.model()
for i in range(3):
item = QtGui.QStandardItem(str(i))
item.setData('MY DATA' + str(i) )
comboModel.appendRow(item)
vLayout.addWidget(self.combo)
def currentIndexChanged(self, index):
print index
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyCombo()
w.show()
sys.exit(app.exec_())
import sys
from PySide import QtGui, QtCore
class MyCombo(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
vLayout=QtGui.QVBoxLayout(self)
self.setLayout(vLayout)
self.combo=QtGui.QComboBox(self)
self.combo.currentIndexChanged.connect(self.currentIndexChanged)
comboModel=self.combo.model()
for i in range(3):
item = QtGui.QStandardItem(str(i))
comboModel.appendRow(item)
self.combo.setItemData(i,'MY DATA' + str(i))
vLayout.addWidget(self.combo)
def currentIndexChanged(self, index):
print self.combo.itemData(index)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyCombo()
w.show()
sys.exit(app.exec_())
This should work for you i think
Working solution is posted below.
While using item.setData() method we should specify a Role with which we associate the data.
class MyCombo(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
vLayout=QtGui.QVBoxLayout(self)
self.setLayout(vLayout)
self.combo=QtGui.QComboBox(self)
self.combo.currentIndexChanged.connect(self.currentIndexChanged)
comboModel=self.combo.model()
for i in range(3):
item = QtGui.QStandardItem(str(i))
item.setData('MY DATA' + str(i), QtCore.Qt.UserRole )
comboModel.appendRow(item)
vLayout.addWidget(self.combo)
def currentIndexChanged(self, index):
modelIndex=self.combo.model().index(index,0)
print self.combo.model().data(modelIndex, QtCore.Qt.UserRole)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
w = MyCombo()
w.show()
sys.exit(app.exec_())

Categories

Resources