【发布时间】:2020-03-22 15:42:49
【问题描述】:
在 QLineEdit 中单击输入时,我必须将焦点设置在 QPushButton 上,并且我能够实现相同的效果,但问题是按钮单击时要执行的操作也会被触发。虽然我没有点击按钮,只调用 setFocus() 代码如下:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QPushButton, QMessageBox, QLineEdit, QDialog
import sys, time
class App(QDialog):
def __init__(self):
super().__init__()
self.title = 'PushButton Set Focus'
self.left = 200
self.top = 200
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.lineEdit = QLineEdit('Press Enter', self)
self.lineEdit.move(100, 30)
self.lineEdit.returnPressed.connect(self.__setFocusOnButton)
self.button = QPushButton('Click me', self)
self.button.move(100, 70)
self.button.setAutoDefault(True)
self.button.clicked.connect(self.on_click)
self.show()
def on_click(self):
print('Button Clicked')
def __setFocusOnButton(self):
self.button.setFocus()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
请告诉我是否有一些无需点击即可设置焦点的方法。
【问题讨论】:
-
提供minimal reproducible example。如果代码没有重现问题,那么它无助于理解问题。另一方面,是 QDialog 中的按钮吗?
-
然后使用 QDialog 修改您的示例并检查是否显示了问题,如果是,则使用新代码更新您的问题。
-
实际的按钮在 QDialog 上。我会尝试用 QDialog 写一个 MRE。
标签: python-3.x pyqt5 setfocus