Reputation: 8634
Below is a Qt example that contains an AbstractListModel
and two display widgets that are linked to this model (a ListView
and a LineEdit
):
from PyQt5 import QtCore, QtWidgets
class ListModel(QtCore.QAbstractListModel):
def __init__(self, data_values, tooltips, parent=None):
super().__init__(parent)
self.data_values = data_values
self.tooltips = tooltips
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.data_values)
def data(self, index, role=QtCore.Qt.DisplayRole):
if (role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole):
return self.data_values[index.row()]
elif role == QtCore.Qt.ToolTipRole:
return self.tooltips[index.row()]
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
data_values = ['apple', 'pumpkin', 'orange']
tooltips = [
"Don't accept when offered by evil queen in disguise.",
"Excellent halloween decoration.",
"Good source of Vitamin C.",
]
self.list_model = ListModel(data_values, tooltips)
self.line_edit = QtWidgets.QLineEdit(parent=self)
self.line_edit.setReadOnly(True)
self.list_view = QtWidgets.QListView(parent=self)
self.list_view.setModel(self.list_model)
self.list_view.setCurrentIndex(self.list_model.index(0))
self.mapper = QtWidgets.QDataWidgetMapper(parent=self)
self.mapper.setModel(self.list_model)
self.mapper.addMapping(self.line_edit, 0)
self.mapper.toFirst()
self.list_view.selectionModel().currentRowChanged.connect(self.mapper.setCurrentModelIndex)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.list_view, 0)
layout.insertSpacing(1, 40)
layout.addWidget(self.line_edit, 2)
self.setLayout(layout)
qt_application = QtWidgets.QApplication([])
window = Window()
window.show()
qt_application.exec_()
I have configured the data
method of the AbstractListModel
to supply tooltip texts to linked widgets. A tooltip indeed appears when the mouse cursor is placed over an item in the ListView
. However no tooltip appears when the mouse cursor is placed over the LineEdit
.
I would like for the LineEdit
to display a tooltip with the text provided by the linked AbstractListModel
. Is there any way at all to achieve this?
Upvotes: 2
Views: 1314
Reputation: 11072
It is not possible to achieve this with QDataWidgetMapper
. QDataWidgetMapper
always uses the Qt::EditRole
value of the model. One could suggest to use the overloaded version of addMapping
and a TableModel
with one column (section
) for displaying and one for the tooltip, but this is not possible, because QDataWidgetMapper
only allows you to implement one-to-one mapping:
If the widget is already mapped to a section, the old mapping will be replaced by the new one.
Solution
The easiest solution is to create a slot yourself which you connect to the currentRowChanged
signal and which sets the tooltip (QWidget::setToolTip
) and text (QLineEdit::setText
) manually.
Upvotes: 3