首页 > 解决方案 > QLineEdit 使用按钮从鼠标选择中显示选定的文本

问题描述

我想从小QLineEdit部件中获取选定的文本。我们通过单击一个按钮来获取选定的文本。如果文本是用selectAll. 但如果用鼠标选择文本,它就不起作用。在后一种情况下,将显示一个空字符串。

为什么文本会有如此大的差异以及如何使鼠标选择起作用?

#!/usr/bin/python

import sys
from PyQt5.QtWidgets import (QWidget, QLineEdit, QPushButton, QHBoxLayout,
    QVBoxLayout, QApplication, QMessageBox)
from PyQt5.QtCore import Qt


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        vbox = QVBoxLayout()
        hbox1 = QHBoxLayout()

        self.qle = QLineEdit(self)
        self.qle.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
        self.qle.setText('There are 3 hawks in the sky')

        hbox1.addWidget(self.qle)

        selAllBtn = QPushButton('Select all', self)
        selAllBtn.clicked.connect(self.onSelectAll)

        deselBtn = QPushButton('Deselect', self)
        deselBtn.clicked.connect(self.onDeSelectAll)

        showSelBtn = QPushButton('Show selected', self)
        showSelBtn.clicked.connect(self.onShowSelected)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(selAllBtn)
        hbox2.addSpacing(15)
        hbox2.addWidget(deselBtn)
        hbox2.addSpacing(15)
        hbox2.addWidget(showSelBtn)

        vbox.addLayout(hbox1)
        vbox.addSpacing(20)
        vbox.addLayout(hbox2)

        self.setLayout(vbox)

        self.setWindowTitle('Selected text')
        self.show()

    def onSelectAll(self):
        self.qle.selectAll()

    def onDeSelectAll(self):
        self.qle.deselect()

    def onShowSelected(self):
        QMessageBox.information(self, 'info', self.qle.selectedText())



def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

标签: pythonpyqtpyqt5qlineedit

解决方案


如果源代码被修改:

void QLineEdit::focusOutEvent(QFocusEvent *e)
{
    // ...
    Qt::FocusReason reason = e->reason();
    if (reason != Qt::ActiveWindowFocusReason &&
        reason != Qt::PopupFocusReason)
        deselect();
    // ...

在按下按钮的情况下,QFocusEvent 的原因是 Qt::MouseFocusReason,因此将删除选择。

一种解决方法是在删除选择之前获取所选文本并再次设置:

class LineEdit(QLineEdit):
    def focusOutEvent(self, e):
        start = self.selectionStart()
        length = self.selectionLength()
        super().focusOutEvent(e)
        self.setSelection(start, length)
self.qle = LineEdit(self)

推荐阅读