对于QLineEdit 单行编辑组件,我们可能需要自定的条件激活编辑模式并关闭它,而LineEdit并没提供相关方法,这就要求我们对它进行重写
以下是对QLineEdit左键双击激活编辑,右键关闭的实现:
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont, QMouseEvent, QFocusEvent
from PySide6.QtWidgets import QApplication,QLineEdit,QWidget,QVBoxLayout,QPushButton
class lineEdit(QLineEdit):
def __init__(self):
super().__init__()
self.setPlaceholderText('请输入:')
self.setFont(QFont('sumHei,8'))
self.setReadOnly(True) #设置只读
self.resize(250,50)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu) #关闭右键上下菜单
def mousePressEvent(self, arg__1: QMouseEvent) -> None: #单击
if arg__1.button() == Qt.MouseButton.RightButton: #右键点击
self.setReadOnly(True)
def mouseDoubleClickEvent(self, arg__1:QMouseEvent) -> None: #双击
if arg__1.button() == Qt.MouseButton.LeftButton: #左键双击
self.setReadOnly(False)
super().mouseDoubleClickEvent(arg__1)
def focusOutEvent(self, arg__1: QFocusEvent) -> None: #失去焦点
self.setReadOnly(True)
super().focusOutEvent(arg__1)
if __name__ == '__main__':
app = QApplication([])
window = QWidget()
layout = QVBoxLayout(window)
layout.addWidget(lineEdit())
layout.addWidget(QPushButton('点击我'))
window.show()
app.exec()
def eventFilter(self, object: QObject, event: QEvent) -> bool:
if object == self.LineEdit and event.type() == QEvent.Type.FocusOut:
self.LineEdit.setReadOnly(True)
本章中我们通过重写QlineEdit的鼠标点击、双击事件和失去焦点事件,并使用现有控件方法,实现了自定义激活编辑和退出,如果有其他要求也可以试着从focusIn(out)Event等事件进行自定义。