python - PyQt:当单元格进入 QCalendarWidget 时发出信号

标签 python qt pyqt signals-slots qcalendarwidget

在我的 Qt 应用程序中,我使用的是 QCalendarWidget,我希望在鼠标进入日历的新单元格时收到通知。我知道 QCalendarWidget 在内部使用 QTableView 继承自 QAbstractItemView这有一个 entered 信号:

This signal is emitted when the mouse cursor enters the item specified by index. Mouse tracking needs to be enabled for this feature to work.

我尝试使用以下代码接收信号:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyCalendar:

    def __init__(self):
        app = QApplication(sys.argv)

        window = QMainWindow()
        cal = QCalendarWidget(window)

        window.resize(320, 240)
        cal.resize(320, 240)

        table = cal.findChild(QTableView)
        table.setMouseTracking(True)
        table.entered.connect(self.onCellEntered)

        window.show()
        sys.exit(app.exec_())

    def onCellEntered(self, index):
        print("CellEntered")

if __name__ == "__main__":
    window = MyCalendar()

但是我的回调函数从未被调用过。你知道为什么吗?

最佳答案

QCalendarWidget 类使用绕过普通鼠标事件处理程序的自定义 TableView - 因此永远不会发出 enetered 信号。但是,可以通过使用事件过滤器发出执行相同操作的自定义信号来解决这个问题。

这是实现该功能的演示脚本:

import sys
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    cellEntered = QtCore.pyqtSignal(object)

    def __init__(self):
        super(Window, self).__init__()
        self.calendar = QtGui.QCalendarWidget(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.calendar)
        self._table = self.calendar.findChild(QtGui.QTableView)
        self._table.setMouseTracking(True)
        self._table.installEventFilter(self)
        self._index = None
        self.cellEntered.connect(self.handleCellEntered)

    def eventFilter(self, source, event):
        if source is self._table:
            if event.type() == QtCore.QEvent.MouseMove:
                index = QtCore.QPersistentModelIndex(
                    source.indexAt(event.pos()))
                if index != self._index:
                    self._index = index
                    self.cellEntered.emit(QtCore.QModelIndex(index))
            elif event.type() == QtCore.QEvent.Leave:
                self._index = None
        return super(Window, self).eventFilter(source, event)

    def handleCellEntered(self, index):
        print(index.row(), index.column())

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    sys.exit(app.exec_())

关于python - PyQt:当单元格进入 QCalendarWidget 时发出信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044738/

相关文章:

python - 如何获取当前周之前的年份和周数?

python - 如何使用Python代码在Azure上创建虚拟机?

qt - 复制后 QStringList 迭代器的结尾似乎无效

qt - MacOS Qt 上包含 SDL 框架

python - PyQt:获取当前的QTreeWidget项

python - 如何使用 pyqt4 删除表格小部件中的特定行边框

python - 如何在Python中的单个列表中根据给定的x,y值绘制不同的线?

Python CSV 阅读器,CSV 格式化

c++ - 在函数 Qt C++ 中使用 UI 数组

python - 如何从 Qt 对话框获取自定义信号