QLineEditで数値のみの入力させる方法
こちらはMaya Advent Calendar 2018 12月20日の記事です。
時々QLineEditなどを使用する際に数字だけの入力など特定の入力のみに制限したいという場面があったりします
今回はそういう制限を設定する方法を紹介したいと思います
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys from maya import OpenMayaUI from Qt.QtWidgets import * from Qt.QtGui import * from Qt.QtCore import * try: import shiboken except: import shiboken2 as shiboken ptr = OpenMayaUI.MQtUtil.mainWindow() parent = shiboken.wrapInstance(long(ptr), QWidget) class example(QMainWindow): def __init__(self, *args, **kwargs): super(example, self).__init__(parent, *args, **kwargs) self.setGeometry(300, 300, 250, 150) def main(): app = QApplication.instance() ex = example() ex.show() sys.exit() app.exec_() if __name__ == '__main__': main()
まず、上のコードをひな型にコードを記述していきますのでご使用ください
class example(QMainWindow): def __init__(self, *args, **kwargs): super(example, self).__init__(parent, *args, **kwargs) self.setGeometry(300, 300, 250, 150) self.edit = QLineEdit(self) self.edit.move(10,40)
まずはQLineEditを使うためQLineEditを上のように記述していきます
当然、このQLineEdit特に何も指定していないため、文字を入力すると数字以外も入力できる状態が確認できます
QLineEditの入力値を制限する方法がないかPySideのドキュメントを調べてみると下のようなFunctionが存在しているようです
PySide.QtGui.QLineEdit.setValidator(arg__1)
Sets this line edit to only accept input that the validator, v , will accept. This allows you to place any arbitrary constraints on the text which may be entered.
If v == 0, PySide.QtGui.QLineEdit.setValidator() removes the current input validator. The initial setting is to have no input validator (i.e. any input is accepted up to PySide.QtGui.QLineEdit.maxLength() ).
簡単に説明すると任意validatorが受け入れる入力のみを受け入れられるように設定でき、これを使用することで入力するテキストに任意の制約を設定できます
というような内容が書かれています(意訳です)
このsetValidatorを使用すればテキストの制限を設定できそうですね
MayaPython Advent Calendar 2018の21日目の記事は rateionさんのpythonの関数の引数をmaya.cmds風にしてみる。 です
ディスカッション
コメント一覧
まだ、コメントがありません