PyQt5 QTableWidget 多選刪除
在QTableWidget中,呈現TABLE的方式是從1開始
但實際儲存方式,則是從0開始
也就是要刪除看到的第一列,參數要給0
self.ui.tableWidget.removeRow(0) #刪除看到的第一列
self.ui.tableWidget.removeRow(1) #刪除看到的第二列
self.ui.tableWidget.removeRow(N-1) #刪除看到的第N列
但是要多選刪除時
就不是簡單的跑一個迴圈就行了
items = self.ui.tableWidget.selectedIndexes()
wannaDelRows = [item.row() for item in items]
for row in wannaDelRows:
self.ui.tableWidget.removeRow(row)
實際運行會發現,只有第一列正確被刪除,其他列似乎全都不對了?!
錯誤的原因是因為第一列被刪除後,該列後方的所有位置也跟著減-1了!
也就是當你只是單純地使用selectedIndexes()取得多選的列來刪除的話,從第2筆開始的指到row,已經不在是當初user選到要刪除的row了!
那該怎麼解決呢?
很簡單,從後面開始刪除就行了!
為避免user選的item是同一個row不同column
造成同一個row取到2次,導致跑迴圈時刪除到不應該被刪掉的
因此還需要搭配set確保要刪除的row只會被執行一次
將原本的程式碼修改如下
items = self.ui.tableWidget.selectedIndexes()
wannaDelRows = [item.row() for item in items]
wannaDelRowsReverse = sorted(set(wannaDelRows),reverse=True)
for row in wannaDelRowsReverse:
self.ui.tableWidget.removeRow(row)
You should see how my acquaintance Wesley Virgin's biography begins with this SHOCKING and controversial video.
回覆刪除You see, Wesley was in the army-and shortly after leaving-he revealed hidden, "SELF MIND CONTROL" tactics that the government and others used to get anything they want.
As it turns out, these are the same methods lots of celebrities (notably those who "come out of nothing") and elite business people used to become wealthy and famous.
You've heard that you utilize only 10% of your brain.
That's because the majority of your brain's power is UNTAPPED.
Perhaps this conversation has even taken place INSIDE your own head... as it did in my good friend Wesley Virgin's head about 7 years ago, while driving an unregistered, beat-up garbage bucket of a car without a license and $3 on his debit card.
"I'm very frustrated with living payroll to payroll! When will I get my big break?"
You've taken part in those thoughts, am I right?
Your success story is going to happen. You need to start believing in YOURSELF.
WATCH WESLEY SPEAK NOW