我想从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()
如果修改了source code:
在按下按钮的情况下,QFocusEvent的原因是Qt::MouseFocusReason,因此选择将被删除
一种解决方法是在删除所选内容之前获取所选文本并重新设置:
相关问题 更多 >
编程相关推荐