使用上下键在元素之间移动

时间:2019-04-14 07:32:13

标签: python pyqt pyqt5 arrow-keys

我使用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_())

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是覆盖keyPressEvent()方法以检测所需的键,如果希望焦点分别移至上一个或下一个窗口小部件,则通过传递False或True来使用focusNextPrevChild()。 / p>

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)
# ...