Skip to content

[PyQt5] 基本教學(10) 使用鍵盤輸入指令、判斷滑鼠點擊位置

Last Updated on 2021-04-11 by Clay

在 PyQt5 當中,我們常常會使用鍵盤以及滑鼠來操控我們的圖形化界面。在某次製作圖形化界面時遇到這個問題,我就決定要好好地把這方面的知識紀錄下來。


熱鍵設定

首先我們來做個範例的程式:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'board.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(303, 123)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 301, 91))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 303, 25))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "The number you selected: "))


這個程式同樣是使用 Qt Designer 加上 PyUIC 轉換而成,顯示的效果如下:

然後我們來測試最常使用的『熱鍵』:

# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from board import Ui_MainWindow


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ctrl_n = QShortcut(QKeySequence("Space"), self)
        self.ctrl_n.activated.connect(self.displayEvent)

    def displayEvent(self):
        self.ui.label.setText('The number you selected: Space')


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


重要的便是:

QShortcut(QKeySequence("Space"), self)

這一行。這一行的指令會返回一個物件,該物件若被激活(觸發條件就是 Space 空白鍵),就會自動執行:

self.ctrl_n.activated.connect(self.displayEvent)

displayEvent() 為修改 label 內的文字。

本來的樣子。

按下 Space 空白鍵:

我們可以看到 Space 就出現在畫面上。


QKeySequence("Space")

其實是可以接複合按鍵的。比如說今天我們把 Space 改成 ctrl+n:

# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from board import Ui_MainWindow


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ctrl_n = QShortcut(QKeySequence("Ctrl+n"), self)
        self.ctrl_n.activated.connect(self.displayEvent)

    def displayEvent(self):
        self.ui.label.setText('The number you selected: Ctrl+n')


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


Output:

本來的樣子。

按下 Ctrl + n 之後:

這可以說是最簡單的熱鍵實做方法。


滑鼠左右鍵判斷

滑鼠事件其實非常單純,就是重寫我們要判定元件的 mousePressEvent() 事件。

# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from board import Ui_MainWindow


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.ui.label.setText('The number you selected: Left!')

        if event.button() == Qt.RightButton:
            self.ui.label.setText('The number you selected: Right!')


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


Output:

對著視窗點選『左鍵』:

對著視窗點選『右鍵』:

若有什麼想要製作的函式,在判定的底下寫就好。


Read More

Leave a Reply取消回覆

Exit mobile version