我更改了QDoubleSpinbox,因为我想要“。”而不是','但现在setDecimals不起作用...我如何保留qdoublespinbox分别对应于setdecimals的功能并保留我的重写类(或类似的东西/更好的东西)?
我试着做:
return QtWidgets.QWidget.locale().toString(_value, QLatin1Char('f'), QtWidgets.QDoubleSpinBox.decimals())
在textFromValue下,但出现错误:
TypeError: locale(self): first argument of unbound method must have type 'QWidget'
我不明白。我也不相信pyqt5支持QLatin1Char。
from PyQt5 import QtCore, QtGui, QtWidgets
class DotDoubleSpinBox(QtWidgets.QDoubleSpinBox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setDecimals(4)
self.setMinimumWidth(300)
self.setMaximum(9999999999)
def validate(self, text, position):
if "." in text:
state = QtGui.QValidator.Acceptable
elif "," in text:
state = QtGui.QValidator.Invalid
else:
state = QtGui.QValidator.Intermediate
return (state, text, position)
def valueFromText(self, text):
text = text.replace(",", ".")
return float(text)
def textFromValue(self, value):
_value = str(value)
_value = _value.replace(",", ".")
return _value
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.doubleSpinBox = DotDoubleSpinBox(self.centralwidget)
self.doubleSpinBox.setGeometry(QtCore.QRect(260, 110, 80, 32))
self.doubleSpinBox.setObjectName("doubleSpinBox")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 30))
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"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
最佳答案
我发现整个问题比我最初设想的要容易得多。原来,您只需要将语言环境设置为使用'。'的语言环境即可。代替 ','。
self.doubleSpinBox.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
这样就可以了。不管怎样,谢谢几乎能给出完美答案的回答者。
关于python - 使setDecimals与重写的QDoubleSpinBox一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51826478/