python - 改变QTableView的滚动方向

标签 python python-2.7 pyqt pyqt4 qtableview

我一直在环顾四周,似乎找不到任何可以帮助我更改 QTableView 中滚轮滚动方向的示例。这是我尝试的最好尝试。

这就是我水平滚动的方法:

def eventFilter(self, obj, event):
    #some of my widgets are disabled, I can simply do another if for enabled ones

    if obj and obj.isEnabled() and event.type() == QEvent.Wheel and self.shift_key:
        newEvent = QWheelEvent(obj.mapToParent(event.pos()), event.globalPos(),
                               event.delta(), event.buttons(),
                               event.modifiers(), 1)
        QApplication.instance().postEvent(obj.parent(), newEvent)
        return True

    if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Shift:
        self.shift_key = True
        return True
    elif event.type() == QEvent.KeyRelease and event.key() == Qt.Key_Shift:
        self.shift_key = False
        return True

    return QObject.eventFilter(self, obj, event)

当我将鼠标悬停在标题或空白处时,就会出现问题,因为它不会水平滚动,并且还会显示错误

QApplication::postEvent:意外的空接收器

如何使用 scroll + shift 实现水平滚动?

最佳答案

如果您希望当焦点位于 QTableViewviewport() 中时,压力 shitf + 滚动 水平滚动条可能会移动解决方案是覆盖 wheelEvent 方法,创建一个过滤器并将事件发送到 horizo​​ntalScrollBar():

from PyQt4 import QtCore, QtGui

class TableView(QtGui.QTableView):
    def wheelEvent(self, event):
        if event.modifiers() == QtCore.Qt.ShiftModifier:
            QtGui.QApplication.sendEvent(self.horizontalScrollBar(), event)
        else:
            QtGui.QTableView.wheelEvent(self, event)

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        lay = QtGui.QVBoxLayout(self)

        tableview = TableView()
        lay.addWidget(tableview)

        model = QtGui.QStandardItemModel(10, 10)
        tableview.setModel(model)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

关于python - 改变QTableView的滚动方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238046/

相关文章:

python - 更新和切换绘图

python - Tkinter 工作吗?

python - 通过信号杀死子进程,但位置影响?

python - 如何使用断言语句(添加双引号)比较pytest中的列表?

Python Flask heroku 应用程序错误

python - 如何在数据库中使用 QSortFilterProxyModel?

python - uwsgi 服务没有启动

python - 在 Docker Pipenv 上安装 psycopg-binary 时,出现错误:在系统上找不到 Python 3.8

python - Plotly python offline - 点击访问 url?

python - PyQt5 的上下文菜单不显示正确的语言