在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_())
最佳答案
您必须使用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()
是否删除,移动或执行任何其他更改项目位置的操作。关于python - 如何从索引列表中选择QtableWidget中的单元格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50067782/