Issue
How would I populate the context menu action 'Search:' with the display text from the cell which was right-clicked in the QTableView. Ideally i would like the Menu item to show the text of the cell. In this example it would say 'Search: 45' and if the user clicks the action it would set the text of the QLineEdit.
import sys
from PySide import QtCore, QtGui
class Example(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
# controls
model = QtGui.QStandardItemModel(5, 3)
model.setHorizontalHeaderLabels(['NAME', 'AGE', 'CAREER'])
people = [
{'name': 'Kevin', 'age': 5, 'career': 'athlete'},
{'name': 'Maggie', 'age': 13, 'career': 'banker'},
{'name': 'Leslie', 'age': 32, 'career': 'banker'},
{'name': 'Emily', 'age': 45, 'career': 'athlete'},
{'name': 'David', 'age': 27, 'career': 'banker'},
{'name': 'Marie', 'age': 63, 'career': 'secretary'}
]
for row, obj in enumerate(people):
item = QtGui.QStandardItem(obj['name'])
model.setItem(row, 0, item)
item = QtGui.QStandardItem(str(obj['age']))
model.setItem(row, 1, item)
item = QtGui.QStandardItem(obj['career'])
model.setItem(row, 2, item)
proxy_model = QtGui.QSortFilterProxyModel()
proxy_model.setSourceModel(model)
# controls
self.ui_table = QtGui.QTableView()
self.ui_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.ui_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.ui_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.ui_table.setModel(proxy_model)
self.ui_table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.ui_search = QtGui.QLineEdit()
# actions
self.act_search_keyword = QtGui.QAction('Search:', self)
# menu
self.context_menu = QtGui.QMenu('File')
self.context_menu.addAction(self.act_search_keyword)
# lay main
lay_main = QtGui.QVBoxLayout()
lay_main.addWidget(self.ui_search)
lay_main.addWidget(self.ui_table)
self.setLayout(lay_main)
# connections
self.ui_table.customContextMenuRequested.connect(self.open_context_menu)
def open_context_menu(self, point):
self.context_menu.exec_(QtGui.QCursor.pos())
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
Solution
You have to create the menu in the slot and use the position to obtain the data through indexAt()
that returns the QModelIndex
...
self.ui_search = QtGui.QLineEdit()
# lay main
lay_main = QtGui.QVBoxLayout()
lay_main.addWidget(self.ui_search)
lay_main.addWidget(self.ui_table)
self.setLayout(lay_main)
# connections
self.ui_table.customContextMenuRequested.connect(self.open_context_menu)
def open_context_menu(self, point):
context_menu = QtGui.QMenu()
ix = self.ui_table.indexAt(point)
val = ix.data()
context_menu.addAction("Search: {}".format(val))
action = context_menu.exec_(self.ui_table.mapToGlobal(point))
if action:
self.ui_search.setText(val)
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.