Setting focus on QlineEdit widget(将焦点放在 QlineEdit 小部件上)
问题描述
我正在尝试组合一个简单的小部件,其中焦点自动放在 QLineEdit 小部件上(它用于条形码扫描仪输入,我不希望最终用户必须单击小部件).
I am trying to put together a simple widget where the focus is automatically put to a QLineEdit widget (It is for a barcode scanner input, and I don't want the end users to have to click in the widget).
相关代码如下:
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 小部件上.我猜这是我错过的非常明显的东西,但我已经挖了一段时间试图找到它,但还没有偶然发现它.
And it doesn't want to put the focus on the lineEdit widget. I'm guessing its something really obvious that I've missed, but I've been digging around for a while trying to find it, and haven't stumbled upon it yet.
推荐答案
你必须使用 setFocus()
小部件显示后.
You must use setFocus()
after the widget is displayed.
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()
这篇关于将焦点放在 QlineEdit 小部件上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将焦点放在 QlineEdit 小部件上
基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01