我在应用程序中使用QLineEdit小部件来输入和编辑数值(float)值。我希望显示浮点值的四舍五入版本,同时保持完整的内部精度。只有在编辑QLineEdit字段时,才应显示完整的位数。在
有三个原因需要这样做:
对于我的GUI来说,复杂的值需要太多的空间
用户界面允许在日志和线性表示之间进行选择,我想隐藏由此产生的数值误差。
简单地舍入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_())
我试图混合使用信号槽连接(
editingFinished
)和eventFilter。但是,我遇到了一些奇怪的bug,这些bug可能是由一些竞争条件引起的,或者仅仅是因为代码背后的逻辑变得过于扭曲。不管怎样,下面的片段很好用,也许对某些人有帮助:看来行为应该是这样的:
这意味着当按下return或enter时,取整不能(因为在这种情况下,行编辑不会失去焦点)。在
通过以下更改可以实现上述行为:
附言:
您可能应该在示例中添加一个按钮或其他内容,以便测试更改焦点的效果。在
相关问题 更多 >
编程相关推荐