Consider a QTableWidget and two buttons “move up” and “move down”. Clicking on move up, the current row should move up one row, analogously for “move down”.
What’s the easiest way to implement the corresponding move up and move down functions?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I have revised my answer because it did not have enough detail previously
The process involves connecting your buttons to a slot (or slots) that will look at the current selection, and move them by taking them from the view, and inserting them into new locations.
The following example is actually using a QTableView + QStandardItemModel. The reason is because QTableWidget is much more limited since you can only use methods from the widget. Its a lot easier to be able to work directly with the model and selection model. Although, it is possible to rework this example for a QTableWidget if you use
takeItem()multiple times to build up each row…Here is a fully working example:
The init is simple and just sets up the table, model, and buttons. We connect both buttons to the same method using
functools.partial, which is really convenient for wrapping up the same function call with different args. Then the table is just filled with 20×6 data.When a button is clicked, we make sure they have selected rows. For each selected row, we resolve its item (for re-selection later once it has moved), and determine the new row number by either adding or subtracting one. We also make sure its within the valid range to move, otherwise we skip it. Finally, we call
takeRow()to remove the entire row as a list of indexes, and then insert that row back into the new row number. After that loop, we use the items we saved to look up the new indexes and reselect them again.