【发布时间】:2016-07-22 07:46:13
【问题描述】:
我在我的应用程序中使用 QLineEdit 小部件来输入和编辑数字(浮点)值。我想显示浮点值的四舍五入版本,同时保持完整的内部准确性。只有在编辑 QLineEdit 字段时,才应显示完整的位数。
出于三个原因需要这样做:
复杂的值需要太多空间用于我的 GUI
UI 允许在对数和线性表示之间进行选择,我想隐藏由此产生的数字错误。
仅对 QLineEdit 中包含和显示的值进行四舍五入不是一种选择,因为在编辑显示的值时会失去准确性
有人知道这个问题的巧妙解决方案吗?
您在下面找到一个 MWE,完整代码 (pyfda) 使用小部件的动态实例化和其他丑陋的东西。
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import numpy as np
import sys
from PyQt4 import QtGui
class InputNumFields(QtGui.QWidget):
def __init__(self, parent):
super(InputNumFields, self).__init__(parent)
self.edit_input_float = 10*np.log10(np.pi) # store in log format
self._init_UI()
def _init_UI(self):
self.edit_input = QtGui.QLineEdit()
self.edit_input.editingFinished.connect(self.store_entries)
self.lay_g_main = QtGui.QGridLayout()
self.lay_g_main.addWidget(self.edit_input, 0, 0)
self.setLayout(self.lay_g_main)
self.get_entries()
def store_entries(self):
""" Store text entry as log float"""
self.edit_input_float = 10*np.log10(float(self.edit_input.text()))
self.get_entries()
def get_entries(self):
""" Retrieve float value, delog and convert to string """
self.edit_input.setText(str(10**(self.edit_input_float/10)))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mainw = InputNumFields(None)
app.setActiveWindow(mainw)
mainw.show()
sys.exit(app.exec_())
【问题讨论】:
-
您可以创建另一个变量来保存您的数字的四舍五入版本,并在“主要”数字更改等时更新它。
-
是的,我曾考虑保留所有变量的“影子副本”。但是,每次单击它或更改显示模式(lin/log/ ...)时,您都必须将未截断的值复制回 QLineEdit。我仍然希望有更简单的解决方案...
标签: python floating-point pyqt qlineedit