How to get the row under the cursor for a QTableWi

2019-01-28 10:39发布

Is there a way to get the row number under the mouse pointer? I want to remove a row without knowing the row number, but with just the cursor position.

EDIT:

enter image description here

In This image you can add projects for the Asset Library. When the Delete Bin is clicked the row should be removed. The best way would be to query the ROW number under the Mouse pointer while the bin is clicked. Where the row number is parsed to the removeRow function. I dont know how to make use of the QPointer for that. And cellEntered needs row/col values which wont stay the same when new rows are added or remvoved.

标签: qt pyqt pyside
3条回答
仙女界的扛把子
2楼-- · 2019-01-28 11:16

Probably what you need is to use the signal cellEntered and the slot removeRow (if you're using QTableWidget). See the docs here for PySide and here for PyQt. You may also need to look up this topic in the Qt docs here.

查看更多
迷人小祖宗
3楼-- · 2019-01-28 11:17

Assuming that the removal is supposed to happen e.g. on a mouse click, all views have the indexAt method, that will map any cursor/mouse location to a model index:

modelIndex = myView.indexAt(cursorLocation) # where cursorLocation is a QPoint instance

With that, it's straightforward to make changes to the model.

Alternatively, similar to doru's answer, views also implement the entered signal and others, notifying you of mouse actions on a certain modelindex:

http://qt-project.org/doc/qt-4.8/qabstractitemview.html#signals

查看更多
闹够了就滚
4楼-- · 2019-01-28 11:29

There are a number of approaches that could solve this problem. Some can involve cursor location, and others can get into the table events and signals. A problem with using the QCursor to solve this, is if someone triggers the button with the keyboard as opposed to the mouse click, which means the cursor position might not reflect the correct row.

Since you are already using the high-level QTableWidget, then here is a really simple way to do it:

from functools import partial

class Table(QtGui.QWidget):

    def __init__(self):
        super(Table, self).__init__()

        self.table = QtGui.QTableWidget(3, 2, self)

        for row in xrange(3):
            item = QtGui.QTableWidgetItem("Item %d" % row)
            self.table.setItem(row, 0, item)

            button = QtGui.QPushButton("X", self.table)
            self.table.setCellWidget(row, 1, button)

            button.clicked.connect(partial(self._buttonItemClicked, item))

        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.table)

    def _buttonItemClicked(self, item):
        print "Button clicked at row", item.row()

In this example, we just bake the item of the first column into the clicked callback, so when you click them they have a reference for asking the row number. The approach would be different for lower level model/view.

查看更多
登录 后发表回答