PyQt:将注意力集中在QlineEdit小部件上

时间:2018-03-22 01:02:07

标签: python pyqt pyqt5

我正在尝试整合一个简单的小部件,其中焦点自动放入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小部件上。我猜测我错过了一些非常明显的东西,但是我一直在寻找它,并且还没有找到它,但还没有发现它。

谢谢!

1 个答案:

答案 0 :(得分:4)

显示小部件后,您必须使用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()