在QtableWidget中,我想在查询数据库时存储选定的单元格,并将之前选择的单元格返回到选中状态。我刷新QtableWidget上的项目会清除选择。用户可以选择不连续的单元格范围。
在使用QtableWidget.selectedIndexes()刷新数据之前获取所选单元格没有问题。
我已经尝试循环遍历索引列表并使用setCurrentIndex,但这只留给我最后一个索引。我已经没想完了。如何根据存储的索引恢复选定的单元格区域?
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from room_chart import *
from datetime import datetime, timedelta
class Guest_form(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self)
self.ui = Ui_rooms_chart()
self.ui.setupUi(self)
self.build_chart()
self.ui.book.clicked.connect(self.book)
def book(self):
self.indexes = self.ui.room_chart.selectedIndexes()
#Do stuff
self.build_chart()
#This has the right behaviour but only selects the last index
for x in range(len(self.indexes)):
self.ui.room_chart.setCurrentIndex(self.indexes[x])
self.ui.room_chart.setFocus()
def build_chart(self):
self.ui.room_chart.setRowCount(0)
self.ui.room_chart.setColumnCount(0)
col_labels = []
for x in range(8):
current_day = datetime.now() + timedelta(days=x)
col_labels.append(current_day.strftime('%a') + '\n' + current_day.strftime('%d/%m/%y'))
self.ui.room_chart.setColumnCount(len(col_labels))
self.ui.room_chart.setHorizontalHeaderLabels(col_labels)
row_labels = []
for x in range(8):
row_labels.append(str(x))
self.ui.room_chart.setRowCount(len(row_labels))
self.ui.room_chart.setVerticalHeaderLabels(row_labels)
self.button = QPushButton(self.ui.room_chart)
self.button.setText("Push me")
self.ui.room_chart.setCellWidget(0 , 0, self.button)
if __name__=="__main__":
app=QApplication(sys.argv)
myapp = Guest_form()
myapp.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
您必须使用select()
的QItemSelectionModel
方法:
def book(self):
persistenIndex = map(QPersistentModelIndex, self.ui.room_chart.selectedIndexes())
#Do stuff
self.build_chart()
for pix in persistenIndex:
ix = QModelIndex(pix)
self.ui.room_chart.selectionModel().select(ix, QItemSelectionModel.Select)
self.ui.room_chart.setFocus()
注意: 它将QModelIndex
转换为QPersistentModelIndex
以避免出现问题,因为不知道build_chart()
是否删除,移动或执行任何其他操作更改项目位置的操作。