簡體   English   中英

嘗試將 4x4 鍵盤與 pyqt5 gui 應用程序一起使用

[英]trying to use 4x4 keypad with pyqt5 gui application

我正在嘗試使用帶有基於 pyqt5 的 GUI 應用程序的 pad4pi 模塊編寫從 4x4 鍵盤(機械)輸入的代碼。

當我嘗試單擊按鈕時,它可以正常工作,但是當我嘗試生成某些事件時,我收到錯誤消息:

QObject::startTimer: Timers can only be used with threads started with QThread
class DigitalClock(QWidget,QThread):
    def __init__(self):
        super().__init__()
        SetupKeyboard.keypad.registerKeyPressHandler(self.printKey)
        self.setWindowTitle("OM SAI RAM")
        self.showFullScreen() 
        #self.setCursor(Qt.BlankCursor)
        button = QPushButton("Click", self) 
        button.clicked.connect(self.change)
        button.move(10,10)    
        button.show()

    def change(self):
        self.newpage = Authentication_page()
        self.close()

    def printKey(self, key):
        if key == 'A':
            self.newpage = Authentication_page()
            self.close()

class Authentication_page(QWidget):
    """
    Class to validate authentication.
    """
    def __init__(self):
        super().__init__()
        self.showFullScreen() 
        self.maindesign()

    def maindesign(self):
        """Method to design main page"""
        ####Label###
        self.admin_header = QLabel("Admin Panel", self)
        self.admin_header.setStyleSheet("font-size:40px")
        self.admin_header.move(130, 10)
        self.admin_header.show() 

當我單擊按鈕代碼工作正常但當我按下機械按鈕時,代碼凍結並顯示錯誤消息。

registerKeyPressHandler 分配的處理程序在監視鍵的線程中執行,在您的情況下,printKey 在您嘗試創建小部件的輔助線程中執行,但 Qt 禁止這樣做。

解決方案是創建一個 QObject 並通過發送按下的鍵來發出信號(因為信號是線程安全的),然后連接到接收信息的插槽:

from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject
from PyQt5.QtWidgets import QLabel, QPushButton, QWidget

from pad4pi import rpi_gpio


class KeypadManager(QObject):
    keyPressed = pyqtSignal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        factory = rpi_gpio.KeypadFactory()
        self._keypad = factory.create_4_by_4_keypad()
        self._keypad.registerKeyPressHandler(self._key_press_handler)

    def _key_press_handler(self, key):
        self.keyPressed.emit(key)


class DigitalClock(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("OM SAI RAM")
        self._keypad_manager = KeypadManager()
        self._keypad_manager.keyPressed.connect(self.printKey)

        # self.setCursor(Qt.BlankCursor)
        button = QPushButton("Click", self)
        button.clicked.connect(self.show_authentication_page)
        button.move(10, 10)

        self.showFullScreen()

    def show_authentication_page(self):
        self.newpage = Authentication_page()
        self.close()

    @pyqtSlot(object)
    def printKey(self, key):
        if key == "A":
            self.show_authentication_page()


class Authentication_page(QWidget):
    # ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM