开发者

PyQt4 how do I find the row number of a Widget in a QGridLayout?

I have a PyQt4 application with a QGridLayout as Layout. This layout has n widgets in it, each on another row, but not on another column. I开发者_开发知识库 have made all the widgets using a constructor. I was wondering, how do I get the row number of a widget in the grid layout, so that when I click on it, it gets that number and I can use it further in my code.

The code looks like this:

...
class sampleWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        ...
        self.show()

....

class mainClass(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QGridLayout()
        self.setLayout(layout)
        for i in xrange(10):
            widget = sampleWidget()
            widget.setObjectName("samplewidget" + i)
            layout.addWidget(i, 0)
        self.show()

 ....

I have made all the necessary imports and all what is needed to run the program, don't worry. My only worry is how to get the row number of a widget created.

If someone is willing to help me I would be very grateful!

Have a great day.


I might be missing something obvious but this is at least one way of doing it.
Edit: I wasn't happy with my first suggestion. Changed it therefore. Might be a bit overboard in regards to the question but should show how to get the information you asked for.

from PyQt4 import QtGui, QtCore
import sys, collections

pos = collections.namedtuple("pos", ("row, column"))

class Widget(QtGui.QWidget):

    itemSelected = QtCore.pyqtSignal(QtGui.QWidget, pos)

    def __init__(self):
        super(Widget, self).__init__()
        layout = QtGui.QGridLayout(self)
        for y in range(0, 11):
            layout.addWidget(QtGui.QLabel("Row: %d" % y, self), y, 0)
            for x in range(1,4):
                layout.addWidget(QtGui.QLabel("QLabel"), y, x)
        self.itemSelected.connect(self.onItemSelected)

    def mousePressEvent(self, event):
        widget = self.childAt(event.pos())
        if isinstance(widget, QtGui.QLabel): # Or whatever type you are looking for
            self._handleEvent(widget)
        return QtGui.QWidget.mousePressEvent(self, event)

    def _handleEvent(self, widget):
        layout = self.layout()
        index = layout.indexOf(widget)
        row, column, cols, rows = layout.getItemPosition(index)
        self.itemSelected.emit(widget, pos(row, column))

    def onItemSelected(self, widget, pos):
        print "%s at %s" % (widget, pos)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    wnd = Widget()
    wnd.show()
    sys.exit(app.exec_())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜