使用Up-Down键在元素之间移动

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Up-Down键在元素之间移动相关的知识,希望对你有一定的参考价值。

我使用PyQt5Python3.7制作节目。如何使用箭头键而不是tab键移动元素? (例如使用向下键从button移动到textbox

import sys
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QMainWindow, QPushButton, QFileSystemModel, QTreeView, 
    QFileDialog, QComboBox
from PyQt5.QtCore import pyqtSlot


class App(QMainWindow):

    def __init__(self):
        super(App, self).__init__()

        self.title = 'by Qt5 and python 3.7'
        self.left = 10
        self.top = 10
        self.width = 1000
        self.height = 500

        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.label = QLabel('File Name: ')
        self.label.move(20, 20)

        self.btn_browse = QPushButton('Browse', self)
        self.btn_browse.move(50, 20)
        self.btn_browse.clicked.connect(self.on_click)

        self.textbox = QLineEdit(self)
        self.textbox.move(170, 20)
        self.textbox.resize(280, 40)

        self.page_view = QLineEdit(self)
        self.page_view.move(20, 100)
        self.page_view.resize(800, 400)

        self.show()

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')
        # self.openFileNameDialog()
        # self.saveFileDialog()

if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = App()
        sys.exit(app.exec_())
答案

一种可能的解决方案是覆盖keyPressEvent()方法以检测所需的密钥,并通过传递False或True来使用focusNextPrevChild(),如果您希望焦点分别转到上一个或下一个窗口小部件。

from PyQt5.QtCore import pyqtSlot, Qt


class App(QMainWindow):
    # ...
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Down:
            self.focusNextPrevChild(True)
        elif e.key() == Qt.Key_Up:
            self.focusNextPrevChild(False)
# ...

以上是关于使用Up-Down键在元素之间移动的主要内容,如果未能解决你的问题,请参考以下文章

Python PyGOobject treeview:使用 Tab 键在单元格之间移动后确认编辑

使用向上和向下的文本框键在 datagridview 中移动

无法使用箭头键在诅咒中移动光标 (C)

如何禁止tab键在对话框内的编辑控件和按钮之间切换焦点?

在导航抽屉管理的片段之间移动

在没有娱乐的片段之间移动 - Kotlin