Pyside2: How to use qlineedit with qdoublevalidator in maya

Hello guys,

In Maya with the help of pyside2 tools this can be created. This code block will help you create an empty block in which you can write numbers with decimals. But this code will explain more about how to limit the value in the empty block(qlineedit).Note: Before we start the explanation, if you copy the code in maya or any texteditor just remove the indentation and press tab/4 spaces, otherwise it might give you syantax error
The first 2 lines are modules
import maya.cmds as cmds
from PySide2 import QtGui, QtWidgets

Creating and setting the value of qlineedit(empty block)
test_lineedit = QtWidgets.QLineEdit(“1.0”)

Below mentioned link will give you in-depth info about qlineedit, kindly read through the doc carefully to understand.
qlineedit command reference


Setting limit in qlineedit
You can set any value but there is a catch — below 0.0 and above 500000.0 the value wont be printed or returned in the script editor. The decimal limit is set 3, you wont be able to type more than 3 values and test_lineedit is parent.
test_range = QtGui.QDoubleValidator(0.0, 500000.0, 3, test_lineedit)#Format of writing the decimal in the
Setting the qlineedit for accepting only float values

qlineedit command reference

qlineedit test_float_validator = test_lineedit.setValidator(test_range)

Create a return value from qlineedit

Note that if there is a validator set on the line edit, the returnPressed() / editingFinished() signals will only be emitted if the validator returns Acceptable.

qlineedit command reference

Well you can even choose direct approach without using an “if” statement, there is no hard and fast rule. go ahead and comment the “if” statement and remove indentation and run, experiment.

def trying():

    print test_lineedit.text()

if test_range.validate(test_lineedit.text(), 1):

    test_lineedit.returnPressed.connect(trying)

Below is the complete code, sorry there were some errors i have fixed.

import maya.cmds as cmds

from PySide2 import QtGui, QtWidgets

"""
How to write a floating value in QLineEdit
You can only set the length of digits after decimal
"""

def trying():

    print test_lineedit.text()

test_lineedit = QtWidgets.QLineEdit("1.0")

test_range = QtGui.QDoubleValidator(0.0, 500000.0, 3, test_lineedit)#Format #of writing the decimal in the qlineedit


test_lineedit.setValidator(test_range)

if test_range.validate(test_lineedit.text(), 1):

    test_lineedit.returnPressed.connect(trying)

test_lineedit.show()