pyqt - QTableWidget header clicked for unique column
Asked Answered
H

0

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?

Herson answered 5/2, 2019 at 11:53 Comment(9)
No. But what is the problem with checking the index?Jeane
Efficiency. Won't it be more efficient if this function is not called on every header click but only on the right one?Herson
Only in a very trivial way. It probably only costs a few milliseconds, so worrying about this is premature micro-optimisation.Jeane
Ok. Thank you for your comments. Should I then close the question?Herson
I suppose someone could have a similar question, so it might save a few duplicates to leave it as it is.Jeane
Yep! You're right, @ekhumoro. Somebody else did have a similar question!Carlock
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.Stoltzfus
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.Fabrication
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.Vaudevillian

© 2022 - 2024 — McMap. All rights reserved.