Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

python - Setting focus on QlineEdit widget

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).

The relevant code looks like this:

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()

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...