【问题标题】:PyQt/PySide Get Decimal Place of selected value in QSpinBOXPyQt/PySide 获取 QSpinBOX 中所选值的小数位
【发布时间】:2016-09-20 10:27:00
【问题描述】:

如何查询QSpinBox(PyQt)中选定值的小数位?

假设 QSpinBox 包含值 631.1205 并且用户选择 3 那么答案应该是十位。(即 6=Hundreds, 3=Tens, 1=Ones, 1=Tenths, 2=Hundredths, 0=Thousandths, 5=Ten-Thousandths )。

【问题讨论】:

  • 用户如何选择“3”?就像在旋转框中选择文本 3 一样?或者有下拉列表吗?或者是什么?如果用户选择了多个数字怎么办?
  • 正常的QSpinBox(没有任何下拉列表),用户将通过鼠标选择。如果用户选择多于一位,结果将是更高的值(即 631 = 百,31 = 十,205 = 百)。

标签: python pyqt pyside


【解决方案1】:

假设您有两个列表,其中包含您要返回的文本(如果适合您的用例,可以扩展到千秒以上): big = ['Ones', 'Tens', Hundreds', '千'] 小 = ['十分之一','百分之','千']

首先,您需要在QSpinBox 中获得对QLineEdit 的引用:

line_edit = spinBox.findChild(QLineEdit)

然后找到选择开始的索引:

selectionStart = line_edit.selectionStart()

接下来查找小数点的索引:

try:
    decimalPoint = str(line_edit.text()).index('.')
except ValueError:
    # no decimal point found so assume the number is an integer
    decimalPoint = len(str(line_edit.text()))

然后计算出你需要返回的东西:

# If something is selected
if selectionStart > -1:
    # if we have selected text starting on the left of the decimal
    if selectionStart < decimalPoint:
        return big[decimalPoint-selectionStart-1]
   # else we selected text starting on the right of the decimal
   else:
        return small[selectionStart-decimalPoint-1]

我建议把它放在一个函数中,并在适当的时候调用它,因为我没有你想要做什么的上下文!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多