簡體   English   中英

在沒有QLineEdit的情況下獲取RFID文本

[英]Get the RFID text without QLineEdit

我有一個QLineEdit,它將獲取RFID標簽的值,並使用接收到的值登錄用戶,我已經設置了QLineEdit,以便在按下Enter鍵時調用登錄功能。

我唯一剩下的問題是QLineEdit是可見的,這不是必需的,因為用戶不會輸入其RFID標簽的值,他們將對其進行掃描,然后掃描儀將輸入該值並按Enter。

rfid_enter = QLineEdit()
rfid_enter.returnPressed.connect(lambda: log_user_in(rfid_enter.text()))


def log_user_in(value):
    print(value) (THIS WILL LOG THE USER IN)

QLineEdit需要具有焦點來獲取鍵盤事件,但是要使其具有焦點必須可見,因此隱藏它並不是解決方案。

正如OP在窗口的注釋中所指出的,只有: 兩個標簽,和一些不處理鍵盤事件的間隔符 ,因此沒有小部件可以攔截該事件,因此窗口可以毫無問題地獲取它們(如果有的話)是其他小部件,例如QLineEdits,QTextEdit,QSpinBox等,邏輯可能會更改)。

考慮到上述情況,我實現了以下邏輯:

import string
from PyQt5 import QtCore, QtWidgets


class Widget(QtWidgets.QWidget):
    returnPressed = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(
            QtWidgets.QLabel("My Label", alignment=QtCore.Qt.AlignHCenter),
            alignment=QtCore.Qt.AlignTop,
        )
        self.m_text = ""
        self.returnPressed.connect(self.log_user_in)

    def keyPressEvent(self, event):
        if event.text() in string.ascii_letters + string.digits:
            self.m_text += event.text()
        if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
            self.returnPressed.emit(self.m_text)
            # clear text
            self.m_text = ""
        super(Widget, self).keyPressEvent(event)

    @QtCore.pyqtSlot(str)
    def log_user_in(self, text):
        print(text)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(240, 320)
    w.show()
    sys.exit(app.exec_())

如果整個窗口都是他創建的類,則來自eyllanesc的答案將起作用,但是在我的情況下,布局將更改,因此無法將其用作主窗口。

我采用了一種作弊方法,即嘗試盡可能多地隱藏盒子,最后得到這個結果。


class LogInRFIDListener(QtWidgets.QPlainTextEdit):
    def __init__(self):
        super(LogInRFIDListener, self).__init__()
        self.setTextInteractionFlags(QtCore.Qt.TextEditable)
        self.setCursor(QtCore.Qt.ArrowCursor)
        self.setStyleSheet("border: none; color: transparent;")  # Hide the border around the text box
        self.setCursorWidth(0)  # Hide the cursor

    def keyPressEvent(self, event):  # Major restricting needed
        if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
            log_user_in(self.toPlainText())
        super(LogInRFIDListener, self).keyPressEvent(event)

暫無
暫無

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

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