python - 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()
解决方案
如果源代码被修改:
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)
推荐阅读
- python - 如何将 .h5 文件转换为 .pb 文件?
- iis - 对预检请求的响应未通过访问控制检查:在标头中使用身份验证时,它没有 HTTP ok 状态
- powershell - Powershell 键/值对匹配问题
- r - 可以使用 lm() 将其他变量保持在其平均值,并将回归线绘制在双变量散点图上吗?
- android - 无故自动返回上一个活动画面
- python - 新版 fasttext 中的 predict_proba
- angular - 在 Cordova/Ionic 4 移动应用程序中提供原生广告?
- git - 如何在没有私钥的情况下添加具有 SSH URL 的子模块
- context-free-grammar - 模糊的 CFG 是否有可能转换为 CNF 并变得明确?
- java - API针对不同场景返回不同的对象类型