Qt获取点击项的列位置

Lor*_*nzo 0 qt pyqt pyqt4

我在网格布局中包含三个小部件。当我单击它们时,我想获取它们的列位置,但是我找不到窗口小部件本身的任何属性,并且似乎无法通过访问来获取容器widget.parentWidget()

我可以使用诸如itemAt之类的间接方法,但我宁愿找到一种不太复杂的方法。

jdi*_*jdi 6

您可以简单地询问QGridLayout项在哪里。这是一个例子:

class Widget(QtGui.QWidget):

    def __init__(self):
        super(Widget, self).__init__()
        self.resize(600,600)

        self.layout = QtGui.QGridLayout(self)
        for row in xrange(3):
            for col in xrange(3):
                button = QtGui.QPushButton("Button %d-%d" % (row,col))
                button.clicked.connect(self.buttonClicked)
                self.layout.addWidget(button, row, col)

    def buttonClicked(self):
        button = self.sender()
        idx = self.layout.indexOf(button)
        location = self.layout.getItemPosition(idx)
        print "Button", button, "at row/col", location[:2]
Run Code Online (Sandbox Code Playgroud)

您只需要单击哪个小部件即可。然后,您可以使用来查找布局索引layout.indexOf(widget)。使用索引,您可以查找实际(row, col, rowspan, colspan)使用的layout.getItemPosition(index)

无需遍历列表的全部内容。同样,通过这种方法,您可以获得当前位置,而不是创建项目时存储的任何列位置。添加项目后,可以随时在布局内部移动项目。

如果您发现self.sender()方法“ unpythonic”是因为您必须询问调用方窗口部件是谁,则还可以使用将每个回调与实际的按钮部件预先打包在一起的方法:

from functools import partial 

class Widget(QtGui.QWidget):

    def __init__(self):
        ...
            for col in xrange(3):
                button = QtGui.QPushButton("Button %d-%d" % (row,col))
                cbk = partial(self.buttonClicked, button)
                button.clicked.connect(cbk)
        ...
    def buttonClicked(self, button):
        idx = self.layout.indexOf(button)
Run Code Online (Sandbox Code Playgroud)