PDA

View Full Version : How do I implement column width tracking between 2 QTableViews?



RallyTronics
5th July 2021, 23:53
I have 2 QTableView widgets with the same number of columns in a QVBoxLayout such that one is on top of the other. When I change the width of a column ( via mouse drag ) in the top QTableView , I would like the same column in the bottom QTableView to resize along with it such that the column widths in the top and bottom views are the same.

my environment:
Qt 5.15.12
Windows 10
Visual Studio 2019
C++

Any help would be appreciated.

d_stranz
6th July 2021, 02:32
The QTableView uses QHeaderView instances to manage the horizontal and vertical column headers. You can use the QHeaderView::sectionResized() signal to get notification when a column in one table is resized. Connect this signal to a slot where you call the QHeaderView::resizeSection() method on the other table's header and vice versa.

I would put the code to do this in the widget that contains the two tables in the VBox. Be careful not to cause infinite recursion by calling the resizeSection() method on the same widget that issued the signal as well as not calling resizeSection() when the old and new sizes are the same. I do not know if the sectionResized() signal is sent only when the column is manually resized (ie, interactively with the mouse) or if it is also sent when the size is changed programmatically (through code). You'll have to test that, because that's where recursion could easily happen.

You should also check out this previous post (https://www.qtcentre.org/threads/53612-Solved-Synchronizing-column-widths-between-QTableViews) on a similar problem.

You could have performance issues if your tables are large, because the table layout will be recalculated with every mouse move and call to resizeSection(). If this happens, you can decide to call resizeSection() only on every "nth" signal, when the size difference exceeds a certain amount, or only after a certain time has passed after the mouse has stopped moving (using a 250 ms QTimer, for example), or some combination of these to improve performance.

RallyTronics
6th July 2021, 03:31
Thanks! I will give it a try tomorrow.