1

I want to find QLabel with specific text and focus view on it. Finding widget with desired text is easy, but I couldn't figure out how to focus view on it. The code so far looks like this:

import sys
from PySide import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()

        widget = QtGui.QWidget()
        self.layout = QtGui.QGridLayout()

        for i in range(10):
            label = QtGui.QLabel("aaaa" + str(i))
            self.layout.addWidget(label, i, 0)

        widget.setLayout(self.layout)
        self.toolbar = self.addToolBar("aa")
        findAction = QtGui.QAction('Find', self)
        findAction.triggered.connect(self.find)
        self.toolbar.addAction(findAction)
        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidget(widget)
        self.scroll.setWidgetResizable(True)
        self.setMaximumSize(200, 200)
        self.setCentralWidget(self.scroll)

    def find(self):
        widgets = (self.layout.itemAt(i).widget() for i in range(self.layout.count()))
        for w in widgets:
            if isinstance(w, QtGui.QLabel):
                if w.text() == "aaaa9":
                    w.setFocus()

def main():
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    app.exec_()

if __name__ == "__main__":
    main()

Any ideas how to get focus working?

Mel
  • 5,837
  • 10
  • 37
  • 42
as tek
  • 11
  • 3
  • 1
    What do you mean by "focus view"? `QLabels` aren't editable. You generally set focus on a widget so it receives keyboard input and the user can edit or trigger the control (e.g. `QLIneEdit`, `QPushButton`). Why do you want to set focus on a `QLabel`? – Brendan Abel Jun 22 '16 at 23:18
  • QLabel is just example. Actually i have ~1000 QCheckBox'es and scrolling down and looking for the one with specific text and then checking/unchecking it takes some time. So i want to insert some text and be able to see checkbox with that text without scrolling down. Your suggestion ensureWidgetVisible() will do it. Thanks. – as tek Jun 23 '16 at 14:56

1 Answers1

1

You can use ensureWidgetVisible()

self.scroll.ensureWidgetVisible(w)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118