[英]Pyside6 QDoubleValidator - decimal places are not working as expected
我已經編寫了以下 PySide6 程序並希望限制輸入的小數位。
import sys
from PySide6 import QtWidgets
from PySide6.QtCore import QSize, QLocale
from PySide6.QtGui import QDoubleValidator
from PySide6.QtWidgets import QMainWindow, QLineEdit, QPushButton, QFormLayout, QWidget
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(420, 100))
self.line_edit_2 = QLineEdit()
self.line_edit_4 = QLineEdit()
self.validator_2 = QDoubleValidator(0, 10, 2)
self.validator_2.setNotation(QDoubleValidator.StandardNotation)
self.line_edit_2.setValidator(self.validator_2)
self.validator_4 = QDoubleValidator(0, 10, 4)
self.validator_4.setNotation(QDoubleValidator.StandardNotation)
self.line_edit_4.setValidator(self.validator_4)
self.form_layout = QFormLayout()
self.form_layout.addRow("Double 2", self.line_edit_2)
self.form_layout.addRow("Double 4", self.line_edit_4)
self.button = QPushButton('Validate')
self.form_layout.addRow("", self.button)
self.button.clicked.connect(
lambda: {print(self.line_edit_2.hasAcceptableInput(), self.line_edit_4.hasAcceptableInput())})
self.main_widget = QWidget()
self.main_widget.setLayout(self.form_layout)
self.setCentralWidget(self.main_widget)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
但是當我運行它時,無論我在第三個參數中定義什么(根據此處,它控制數字),我都無法輸入任何小數位數大於 2 的雙精度數。
在寫這個問題時,我自己想出了解決方案。 問題出在系統的語言設置上。 我的系統設置為德語,但我試圖以國際格式輸入帶點的浮點數。 為了讓驗證器在輸入點時使用正確的小數位,必須將其設置為正確的區域設置(如果系統區域設置不同)。 對於上面的示例,我必須添加以下行:
from PySide6.QtCore import QLocale
locale = QLocale(QLocale.English, QLocale.UnitedStates)
self.validator_2.setLocale(locale)
self.validator_4.setLocale(locale)
通過這些更改,驗證器將按預期工作:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.