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

问题描述 投票:2回答:1

我使用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_())
python pyqt pyqt5 arrow-keys
1个回答
1
投票

一种可能的解决方案是覆盖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)
# ...
© www.soinside.com 2019 - 2024. All rights reserved.