【问题标题】:Qt: display tooltip on LineEdit widget that is mapped to AbstractListModelQt:在映射到 AbstractListModel 的 LineEdit 小部件上显示工具提示
【发布时间】:2017-05-23 18:22:47
【问题描述】:

情况

下面是一个 Qt 示例,其中包含一个 AbstractListModel 和两个链接到此模型的显示小部件(一个 ListView 和一个 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_()

我已配置AbstractListModeldata 方法为链接的小部件提供工具提示文本。当鼠标光标放在ListView 中的某个项目上时,确实会出现一个工具提示。但是,当鼠标光标放在LineEdit 上时,不会出现工具提示。

问题

我希望LineEdit 显示一个工具提示,其中包含链接的AbstractListModel 提供的文本。有什么办法可以实现这一目标吗?

【问题讨论】:

    标签: python qt tooltip pyqt5


    【解决方案1】:

    QDataWidgetMapper 无法实现此目的。 QDataWidgetMapper 始终使用模型的 Qt::EditRole 值。可以建议使用addMapping 的重载版本和TableModel,其中一列(section)用于显示,一列用于工具提示,但这是不可能的,因为QDataWidgetMapper 只允许您实现@987654322 @:

    如果小部件已经映射到一个部分,旧的映射将是 替换为新的。

    解决方案

    最简单的解决方案是自己创建一个插槽,将其连接到currentRowChanged 信号并手动设置工具提示 (QWidget::setToolTip) 和文本 (QLineEdit::setText)。

    【讨论】:

    • 啊哈,很高兴知道QDataWidgetMapper 总是使用Qt::EditRole。这已经很好地解释了为什么在我的示例中没有发生任何事情。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 2015-03-24
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多