gpt4 book ai didi

python - 将焦点放在 QlineEdit 小部件上

转载 作者:行者123 更新时间:2023-11-28 20:59:33 25 4
gpt4 key购买 nike

我正在尝试组装一个简单的小部件,其中焦点自动放在 QLineEdit 小部件上(它用于条形码扫描器输入,我不希望最终用户必须单击小部件)。

相关代码如下所示:

from qtmodern import styles, windows
from qtpy import QtGui, QtCore
from qtpy.QtWidgets import *
from qtpy.QtCore import Qt

class MyGui(QWidget):
def __init__(self, parent=None):
super(MyGui, self).__init__(parent)

layout = QVBoxLayout()

self.lineEdit = QLineEdit(self)
self.lineEdit.setPlaceholderText('foobar')
self.lineEdit.setFocusPolicy(Qt.StrongFocus)
self.lineEdit.setFocus()

layout.addWidget(self.lineEdit)

self.setLayout(layout)
self.show()

def main():
app = QApplication([])
styles.dark(app)

g = windows.ModernWindow(MyGui())
g.resize(350,100)
location = (50, 100)
g.move(location[0], location[1])
g.setWindowTitle('SmallTest')

g.show()
app.exec_()

if __name__ == '__main__':
main()

而且它不想将焦点放在 lineEdit 小部件上。我猜它是我错过的非常明显的东西,但我已经挖掘了一段时间试图找到它,但还没有偶然发现它。

最佳答案

您必须使用 setFocus()显示小部件后。

from qtmodern import styles, windows
from qtpy import QtGui, QtCore
from qtpy.QtWidgets import *
from qtpy.QtCore import Qt

class MyGui(QWidget):
def __init__(self, parent=None):
super(MyGui, self).__init__(parent)
layout = QVBoxLayout(self)
self.lineEdit = QLineEdit(self)
self.lineEdit.setPlaceholderText('foobar')
self.lineEdit.setFocusPolicy(Qt.StrongFocus)
layout.addWidget(self.lineEdit)

def main():
app = QApplication([])
styles.dark(app)
gui = MyGui()
g = windows.ModernWindow(gui)
g.resize(350,100)
location = (50, 100)
g.move(*location)
g.setWindowTitle('SmallTest')
g.show()
gui.lineEdit.setFocus()
app.exec_()

if __name__ == '__main__':
main()

关于python - 将焦点放在 QlineEdit 小部件上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49418905/

25 4 0