QLineEdit使用按钮显示鼠标选择中的选定文本

2024-04-26 07:55:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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()

Tags: 文本importselfdefsysvboxclickedqpushbutton
1条回答
网友
1楼 · 发布于 2024-04-26 07:55:19

如果修改了source code

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)

相关问题 更多 >