Pyside - 当QLineEdit获得焦点时选择所有文本

时间:2014-04-15 07:02:32

标签: python qt pyside qlineedit

我是Qt / PySide的新手。我希望QLineEdit在获得焦点时选择其中的所有文字。在获得焦点并选择所有文本后,只有在焦点丢失并再次获得后才能选择所有文本。在QLineEdit获得焦点后更改光标位置时,不应选择所有文本。我该怎么做?

更新:根据Ashwani Kumar的建议,我目前的代码有所改善。我仍然无法让它工作:

import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget
class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)

    def focusInEvent(self, e):
        self.selectAll()      

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(MyLineEdit())
layout.addWidget(MyLineEdit())
top.setLayout(layout)
top.show()
app.exec_()

4 个答案:

答案 0 :(得分:6)

使用focusInEvent,当您单击窗口小部件时,它会被执行,但是在您单击后,它将删除所选文本。

为了解决这个问题,我们必须使用mousePressEvent,这可以通过两种方式完成:

import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget
class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)

    def mousePressEvent(self, e):
        self.selectAll()      

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(MyLineEdit())
layout.addWidget(MyLineEdit())
top.setLayout(layout)
top.show()
app.exec_()

或者你可以通过简单地覆盖基类QLineEdit类来实现:

txt_demo = QtGui.QLineEdit()
txt_demo.mousePressEvent = lambda _ : txt_demo.selectAll()

但是,由于我们正在修改mousePressEvent,因此每当您尝试点击文字时,它始终会先选择所有内容。

答案 1 :(得分:2)

您必须继承QLineEdit,然后使用新类而不是QLineEdit。 例如: -

class MyLineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None)
        super(MyLineEdit, self).__init__(parent)

    def focusInEvent(self, e):
        self.selectAll()


lineedit = MyLineEdit()

答案 2 :(得分:2)

对于未来的访问者,我发布的代码对我有用。由于我是新手,我不确定代码是否包含任何不当行为。如果它可以随意发表评论,我会更新我的代码/答案。代码:

import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget

class LineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent)
        self.readyToEdit = True

    def mousePressEvent(self, e, Parent=None):
        super(LineEdit, self).mousePressEvent(e) #required to deselect on 2e click
        if self.readyToEdit:
            self.selectAll()
            self.readyToEdit = False

    def focusOutEvent(self, e):
        super(LineEdit, self).focusOutEvent(e) #required to remove cursor on focusOut
        self.deselect()
        self.readyToEdit = True

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(LineEdit())
layout.addWidget(LineEdit())
top.setLayout(layout)
top.show()
app.exec_()

答案 3 :(得分:2)

QtCentre上的

QTimer解决方案:

import types
from PyQt4 import QtCore

def bind(func, to):
    "Bind function to instance, unbind if needed"
    return types.MethodType(func.__func__ if hasattr(func, "__self__") else func, to)

...
self.txtSrc.focusInEvent = bind(lambda w, e: QtCore.QTimer.singleShot(0, w.selectAll), self.txtSrc)

此外,所提供的解决方案不需要继承QLineEdit