簡體   English   中英

使用 PyQt5 lineEdit 小部件,是否有任何簡單的方法只能使用整數值?

[英]Using PyQt5 lineEdit widget, is there any simple way only integer values are available?

我嘗試構建一個代碼,在 lineEdit Widget 上輸入某個數字,然后按下按鈕 Widget,我可以將該值作為整數類型獲取。 但我得到的值類型仍然是字符串。 有沒有什么漂亮的方法可以將 lineEdit Widget 中的值類型限制為整數? 另外,如果lineEdit中的值類型不是整數,是否會彈出Messagebox提示輸入錯誤值?

import sys
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QBoxLayout
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit, QPushButton
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt
from PyQt5 import QtGui

class Form(QWidget):
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        self.init_widget()

    def init_widget(self):

        form_lbx = QBoxLayout(QBoxLayout.TopToBottom, parent=self)
        self.setLayout(form_lbx)

        self.le = QLineEdit()
        self.btn = QPushButton("connect")
        self.btn.clicked.connect(self.func1)

        form_lbx.addWidget(self.le)
        form_lbx.addWidget(self.btn)

    def func1(self):
        value = self.le.text()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = Form()
    form.show()
    exit(app.exec_())

您可以使用QIntValidator()將輸入限制為僅整數。 這樣您就知道輸入將只包含數字,並且您可以將文本轉換為 int 而不必擔心錯誤(只要 LineEdit 不為空)。

self.le.setValidator(QIntValidator())

# Accessing the text
value = int(self.le.text())

要了解更多信息,請查看setValidator方法。 您可能還想考慮使用QSpinBox ,它是為整數設計的,可以直接使用QSpinBox.value()返回一個 int

暫無
暫無

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

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