[英]PyQT5: How to use both QLineEdit: Validator and InputMask?
[英]Setting Cursor To The Beginning of QLineEdit With Inputmask In PyQt5
我为桌面软件创建了一个代码。 那,在 QLineEdit 中,我设置了一个输入掩码。 当我运行我的程序并单击该行编辑时,我在行尾看到了我的 cursor position。 下面是我的一些代码....
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(380, 191)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(80, 20, 211, 41))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(80, 110, 211, 41))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_2.setInputMask("00.00")
self.lineEdit_2.setCursorPosition(0)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
在那之后我已经提到了 setCursorPosition(0) 。 但它不起作用。 当我单击我的 lineEdit_2 时,我希望 cursor 在该 lineedit 的开头。
self.lineEdit_2.setInputMask("00.00")
self.lineEdit_2.setCursorPosition(0)
您可以在行编辑上安装事件过滤器并对任何鼠标单击事件做出反应:
from PyQt5 import QtCore, QtWidgets
from ui_mainwindow import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.lineEdit_2.installEventFilter(self)
def eventFilter(self, source, event):
if source == self.lineEdit_2 and event.type() == QtCore.QEvent.MouseButtonPress:
self.lineEdit_2.setFocus(QtCore.Qt.MouseFocusReason)
self.lineEdit_2.setCursorPosition(0)
return True
return super().eventFilter(source, event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
请注意,您应该将上述内容编写在一个单独的脚本中,并将其用作您的主程序; 您发布的代码取自 pyuic 的pyuic
,永远不应修改。 阅读有关使用 Designer的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.