6

I have a QTableWidget of 5 columns with horizontal headers. I need to launch a function when header of column 4 is clicked. Currently, I have a working solution that consists of calling this function for every header clicked and then parsing the index and test if it's the right column.

Here is the current code:

self.table = QtGuiWidgets.QTableWidget()
self.table.horizontalHeader().sectionClicked.connect(self.onHeaderClicked)

def onHeaderClicked(self, logicalIndex):
    if logicalIndex == 4:
        print "ok"

Is there a way to avoid calling this function on every header click but just calling it when the right column header is clicked?

Kevin Lemaire
  • 949
  • 2
  • 12
  • 36
  • No. But what is the problem with checking the index? – ekhumoro Feb 05 '19 at 18:22
  • Efficiency. Won't it be more efficient if this function is not called on every header click but only on the right one? – Kevin Lemaire Feb 06 '19 at 10:35
  • 1
    Only in a very trivial way. It probably only costs a few milliseconds, so worrying about this is premature micro-optimisation. – ekhumoro Feb 06 '19 at 15:25
  • Ok. Thank you for your comments. Should I then close the question? – Kevin Lemaire Feb 06 '19 at 15:40
  • 4
    I suppose someone could have a similar question, so it might save a few duplicates to leave it as it is. – ekhumoro Feb 06 '19 at 15:43
  • 2
    Yep! You're right, @ekhumoro. Somebody else did have a similar question! – Colin Wu Apr 19 '20 at 16:42
  • 1
    The question itself is about a premature micro-optimization, as mentioned by other comments, so it's kinda... eh. But it has the best example of setting up event handling from table headers that I've found so far, so that's really useful. – EL_DON May 06 '20 at 00:18
  • This helped me a lot, thanks. I am still relatively new to PYQT and would really appreciate if you could explain how and why this works. I have used lambda to pass arguments to connect signals in the past but I just do not understand how you manage to pass 'logicalIndex' as an argument to the onHeaderClicked method. If anyone could explain where this input comes from, I would be grateful. – Ruben Jul 14 '20 at 13:14
  • If you care about speed -- Python language is an extremely bad choice, it's already slower up to 50 000 times the highly optimized C++/ASM in compute-bound applications, but it's an extreme case. Typically it's slower only by 1000 times. – Konstantin Burlachenko Jan 20 '22 at 00:10

0 Answers0