How to get QComboBox Item data - python

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_())

Related

How to save/change text of 'QLineEdit' in 'QSettings' and get on 'QPushButton's' call

I want to save/change my 'QLineEdit' text in my app and get again by using 'QPushButton' on some specific position.
The logic is to associate the information with a key, in the following example I show how the text is saved when the text is modified and then the text is retrieved by pressing the button.
from PySide2 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.m_le = QtWidgets.QLineEdit()
self.m_le.textChanged.connect(self.onTextChanged)
self.m_button = QtWidgets.QPushButton("Press Me")
self.m_button.clicked.connect(self.onClicked)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.m_le)
lay.addWidget(self.m_button)
#QtCore.Slot(str)
def onTextChanged(self, text):
settings = QtCore.QSettings()
settings.setValue("text", text)
#QtCore.Slot()
def onClicked(self):
settings = QtCore.QSettings()
text = settings.value("text")
print(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

PyQt5 - resize (limit maximum size) input dialog

I read this: How to resize QInputDialog, PyQt but it didnt work for me, as it seems to be about PyQt4
This is my code snipplet:
def ImportURL(self): #URL dialog aufrufen
InputDialog = QtWidgets.QInputDialog(self)
i, okPressed = InputDialog.getText(self, "Import website", "Site to import:", QtWidgets.QLineEdit.Normal, "https://de.wikipedia.org/wiki/Wikipedia:Hauptseite")
if okPressed:
self.getWebsite(i)
And i tried adding .setFixedSize in the 2nd line. I tried adding InputDialog.setFixedSite(self) between line 2 and 3. Nothing worked, it either crashes or it creates a second, empty window. Am i overlooking something here?
In the answers to the other question do not explain the cause of the problem so in my answer will try to cover as much as possible
Explanation:
The getText() method is a static method, which means that an object is not used, in the method internally if it is used but it is not accessible. So the InputDialog that you create is not the one you show and this you can check using the following code since you will see 2 windows:
def ImportURL(self):
InputDialog = QtWidgets.QInputDialog(self)
InputDialog.show()
i, okPressed = InputDialog.getText(self, "Import website", "Site to import:", QtWidgets.QLineEdit.Normal, "https://de.wikipedia.org/wiki/Wikipedia:Hauptseite")
if okPressed:
self.getWebsite(i)
Solutions:
So there are the following solutions:
Taking advantage of what you have passed as a parent to self, you can obtain the object using findChildren:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
button = QtWidgets.QPushButton(
"Open QInputDialog", clicked=self.ImportURL
)
vlay = QtWidgets.QVBoxLayout(self)
vlay.addWidget(button)
#QtCore.pyqtSlot()
def ImportURL(self):
QtCore.QTimer.singleShot(0, self.after_show)
i, okPressed = QtWidgets.QInputDialog.getText(
self,
"Import website",
"Site to import:",
QtWidgets.QLineEdit.Normal,
"https://de.wikipedia.org/wiki/Wikipedia:Hauptseite",
)
if okPressed:
# self.getWebsite(i)
print(i)
#QtCore.pyqtSlot()
def after_show(self):
size = QtCore.QSize(500, 100)
for d in self.findChildren(QtWidgets.QInputDialog):
if d.isVisible():
d.resize(size)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Do not use the getText() method but create an object that implements the same logic:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
button = QtWidgets.QPushButton(
"Open QInputDialog", clicked=self.ImportURL
)
vlay = QtWidgets.QVBoxLayout(self)
vlay.addWidget(button)
#QtCore.pyqtSlot()
def ImportURL(self):
dialog = QtWidgets.QInputDialog(self)
dialog.resize(QtCore.QSize(500, 100))
dialog.setWindowTitle("Import website")
dialog.setLabelText("Site to Import")
dialog.setTextValue(
"https://de.wikipedia.org/wiki/Wikipedia:Hauptseite"
)
dialog.setTextEchoMode(QtWidgets.QLineEdit.Normal)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
i = dialog.textValue()
print(i)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Update:
The layout of the QInputDialog has QLayout::SetMinAndMaxSize set as sizeConstraint, so the fixed size will not work, the trick is to change it to QLayout::SetDefaultConstraint:
from functools import partial
# ...
#QtCore.pyqtSlot()
def ImportURL(self):
dialog = QtWidgets.QInputDialog(self)
dialog.setWindowTitle("Import website")
dialog.setLabelText("Site to Import")
dialog.setTextValue(
"https://de.wikipedia.org/wiki/Wikipedia:Hauptseite"
)
dialog.setTextEchoMode(QtWidgets.QLineEdit.Normal)
wrapper = partial(self.on_timeout, dialog)
QtCore.QTimer.singleShot(0, wrapper)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
i = dialog.textValue()
print(i)
def on_timeout(self, dialog):
lay = dialog.layout()
lay.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
dialog.setFixedSize(QtCore.QSize(500, 100))

Make QToolBar Items have ContextMenu

How can I add a context menu to the items in my QToolBar. The reason for the context menu, is i want to give each Action a right-click > Delete action. Similar to the Chrome browsers ability to remove bookmarks from the bookmark toolbar. How do i achieve this in Pyside?
import os, sys
from PySide import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.resize(300,200)
self.createToolBars()
self.createActions()
def createToolBars(self):
self.toolBar = self.addToolBar('Presets')
self.toolBar.setIconSize(QtCore.QSize(16,16))
self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
def createActions(self):
self.toolBar.clear()
presets = ['Abby','Kevin','Bob','Mary']
for x in presets:
act = QtGui.QAction(x, self)
act.setData(x)
self.toolBar.addAction(act)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
You have to implement a custom QToolBar and implement the contextMenuEvent method:
import os
import sys
from PySide import QtCore, QtGui
class ToolBar(QtGui.QToolBar):
def contextMenuEvent(self, event):
current_action = self.actionAt(event.pos())
if current_action is None:
return
menu = QtGui.QMenu()
delete_action = menu.addAction("delete")
action = menu.exec_(event.globalPos())
if action == delete_action:
self.removeAction(current_action)
class Example(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.resize(300,200)
self.createToolBars()
self.createActions()
def createToolBars(self):
self.tool_bar = ToolBar('Presets', self)
self.addToolBar(self.tool_bar)
self.tool_bar.setIconSize(QtCore.QSize(16,16))
self.tool_bar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
def createActions(self):
self.tool_bar.clear()
presets = ['Abby','Kevin','Bob','Mary']
for x in presets:
act = QtGui.QAction(x, self)
act.setData(x)
self.tool_bar.addAction(act)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

How do I get a clicked item in a QTreeWidget?

I have a two-dimensional QTreeWidget, how can I get an Item by clicking on it? I use PyQt5. I have this part of the code, but it gets only the first item of the selected row (or any other by changing the baseNode.text(#))
...
self.treeWidget.itemSelectionChanged.connect(lambda: loadAllMessages())
def loadAllMessages():
getSelected = self.treeWidget.selectedItems()
if getSelected:
baseNode = getSelected[0]
getChildNode = baseNode.text(0)
print(getChildNode)
...
You just have to use the itemClicked signal sent by the QTreeWidgetItem and the clicked column:
Example:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
tree = QtWidgets.QTreeWidget()
tree.setColumnCount(2)
lay.addWidget(tree)
for i in range(4):
parent_it = QtWidgets.QTreeWidgetItem(["{}-{}".format(i, l) for l in range(2)])
tree.addTopLevelItem(parent_it)
for j in range(5):
it = QtWidgets.QTreeWidgetItem(["{}-{}-{}".format(i, j, l) for l in range(2)])
parent_it.addChild(it)
tree.expandAll()
tree.itemClicked.connect(self.onItemClicked)
#QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
def onItemClicked(self, it, col):
print(it, col, it.text(col))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

Python: PyQt QTreeview example - selection

I'm using Python 2.7 and Qt designer and I'm new to MVC:
I have a View completed within Qt to give me a directory tree list, and the controller in place to run things. My question is:
Given a Qtree view, how may I obtain a directory once a dir is selected?
Code snap shot is below, I suspect it's SIGNAL(..) though I'm unsure:
class Main(QtGui.QMainWindow):
plot = pyqtSignal()
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# create model
model = QtGui.QFileSystemModel()
model.setRootPath( QtCore.QDir.currentPath() )
# set the model
self.ui.treeView.setModel(model)
**QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)**
def test(self):
print "hello!"
The signal you're looking for is selectionChanged emmited by the selectionModel owned by your tree. This signal is emmited with the selected item as first argument and the deselected as second, both are instances of QItemSelection.
So you might want to change the line:
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)
to
QtCore.QObject.connect(self.ui.treeView.selectionModel(), QtCore.SIGNAL('selectionChanged()'), self.test)
Also I recommend you to use the new style for signals and slots. Redefine your test function as:
#QtCore.pyqtSlot("QItemSelection, QItemSelection")
def test(self, selected, deselected):
print("hello!")
print(selected)
print(deselected)
Here you have a working example:
from PyQt4 import QtGui
from PyQt4 import QtCore
class Main(QtGui.QTreeView):
def __init__(self):
QtGui.QTreeView.__init__(self)
model = QtGui.QFileSystemModel()
model.setRootPath( QtCore.QDir.currentPath() )
self.setModel(model)
QtCore.QObject.connect(self.selectionModel(), QtCore.SIGNAL('selectionChanged(QItemSelection, QItemSelection)'), self.test)
#QtCore.pyqtSlot("QItemSelection, QItemSelection")
def test(self, selected, deselected):
print("hello!")
print(selected)
print(deselected)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
PyQt5
In PyQt5 is a little bit different (thanks to Carel and saldenisov for comments and aswer.)
... connect moved from being an object method to a method acting upon the attribute when PyQt went from 4 to 5
So instead the known:
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)
now you write:
class Main(QTreeView):
def __init__(self):
# ...
self.setModel(model)
self.doubleClicked.connect(self.test) # Note that the the signal is now a attribute of the widget.
Here is a the example (by saldenisov) using PyQt5.
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication
class Main(QTreeView):
def __init__(self):
QTreeView.__init__(self)
model = QFileSystemModel()
model.setRootPath('C:\\')
self.setModel(model)
self.doubleClicked.connect(self.test)
def test(self, signal):
file_path=self.model().filePath(signal)
print(file_path)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
In PyQt5 it can be done in this way:
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication
class Main(QTreeView):
def __init__(self):
QTreeView.__init__(self)
model = QFileSystemModel()
model.setRootPath('C:\\')
self.setModel(model)
self.doubleClicked.connect(self.test)
def test(self, signal):
file_path=self.model().filePath(signal)
print(file_path)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
If I understand the question correctly you would like the directory or file name selected.
This is what I do:
from PyQt4 import QtGui
from PyQt4 import QtCore
# ---------------------------------------------------------------------
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(600,400)
self.setWindowTitle("Treeview Example")
self.treeview = QtGui.QTreeView(self)
self.treeview.model = QtGui.QFileSystemModel()
self.treeview.model.setRootPath( QtCore.QDir.currentPath() )
self.treeview.setModel(self.treeview.model)
self.treeview.setColumnWidth(0, 200)
self.setCentralWidget(self.treeview)
self.treeview.clicked.connect(self.on_treeview_clicked)
# ---------------------------------------------------------------------
#QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeview_clicked(self, index):
indexItem = self.treeview.model.index(index.row(), 0, index.parent())
# path or filename selected
fileName = self.treeview.model.fileName(indexItem)
# full path/filename selected
filePath = self.treeview.model.filePath(indexItem)
print(fileName)
print(filePath)
# ---------------------------------------------------------------------
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I tried this alternative to get the file name...
Instead of:
indexItem = self.treeview.model.index(index.row(), 0, index.parent())
# path or filename selected
fileName = self.treeview.model.fileName(indexItem)
I tried:
# path or filename selected
fileName = index.internalPointer().fileName
Which also seems to work...

Categories

Resources