[PyKDE] Getting cell coordinates in QTable's contextMenuEvent (code snippet included).

Baz Walter bazwal at ftml.net
Thu Dec 22 02:23:12 GMT 2005


On Tuesday 20 Dec 2005 19:21, kgi wrote:
> Hi there.
>
> I'm adding a context menu to a QTable widget, and am trying to work out
> which cell has received the context menu event. I'm using the approach
> given in the code snippet below.
>
> I was originally stumped that the coordinates received by
> contextMenuEvent() didn't seem to reflect the table being scrolled, but I
> found a workaround based upon [1].
>
> Now my problem is that the row/col system seems to be asymmetrical; that
> is:
>
> (all clicks are 'right' clicks):
>
>  - clicking on the vertical header reports 'row = 0'
>  - clicking on the row labelled '1' reports 'row = 1'
>
> But:
>
>  - clicking on the horizontal header reports 'col = 0'
>  - clicking on the column labelled '1' reports 'col = 0'
>  - clicking in the last row (labelled '40') reports 'row = -1'
>
> Does anyone have any idea why this is the case and what the 'right' way to
> work around it would be?

The situation is even worse than this suggests, because right-clicking on the 
extreme right and left of a cell will give different results. Clearly, some 
special handling is required, but fortunately qt has already done this for 
you. Just connect up a handler to QTable.contextMenuRequested (see below) and 
the problem is solved.

HTH
--
Baz Walter

>
> =======================================================
>
> import sys
>
> from qt import *
> from qttable import QTable
>
> class MyTable ( QTable ):
>
>     def __init__ ( self, *args ):
>         QTable.__init__ ( self, *args )
          self.connect(self, SIGNAL(
		       "contextMenuRequested(int, int, const QPoint &)"),
		       self.contextMenu)

      def contextMenu(self, row, col, pos):
          print "row: ", row
          print "col: ", col
          print "X: ", pos.x()
          print "Y: ", pos.y()

[snip]
> if __name__ == '__main__':
>
>     numRows = 40
>     numCols = 5
>
>     app = QApplication ( sys.argv )
>     table = MyTable ( numRows, numCols )
>
>     table.show()
>     app.setMainWidget ( table )
>     app.exec_loop()
>
> ==========================================================
>
> [1] http://lists.trolltech.com/qt-interest/2002-01/thread00017-0.html
>




More information about the PyQt mailing list