帮助实现代码,以便当您单击表格中的单元格时,小部件单元格会更改其颜色,当您再次单击它时,它会再次变为白色
我正在尝试实现文件管理器。
代码:
def onClicked(self, cell):
if not self.highlight_mode:
print(cell)
if cell.text() == '..':
self.path = str(Path(self.path).parent)
print(self.path)
else:
if not os.path.isfile(self.path + "\\" + str(cell.text())):
self.path = self.path + "\\" + str(cell.text())
print(self.path)
try:
os.chdir(self.path)
self.list_dir = os.listdir(self.path)
self.list_dir.insert(0, '..')
except:
buttonReply = QMessageBox.question(self, 'ERROR', "ERROR",
QMessageBox.Ok, QMessageBox.Ok)
self.update_table()
else:
if cell.text() != '..':
self.list_with_select.append(self.path + '\\' + str(cell.text()))
print(self.list_with_select)
def update_table(self):
self.tableWidget.clear()
self.tableWidget.setRowCount(len(self.list_dir))
self.tableWidget.setColumnCount(1)
count = 0
for nel in self.list_dir:
self.tableWidget.setItem(0, count, QTableWidgetItem(nel))
count += 1
def cut(self):
for i in self.list_with_select:
shutil.move(i, self.path + '\\')
self.list_with_select.clear()
def highlight_m(self):
print('recup')
if not(self.highlight_mode):
self.highlight_mode = True
else:
self.highlight_mode = False
print(self.highlight_mode)
最佳答案
您必须切换与每个元素的 Qt::BackgroundRole 函数关联的 QBrush。您可以使用 itemClicked 但这可能会失败,因为并非 QTableWidget 中的所有项目都有关联的 QTableWidgetItem,因此最好使用关联的 QModelIndex 返回的单击信号
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.tableWidget = QtWidgets.QTableWidget()
self.setCentralWidget(self.tableWidget)
self.tableWidget.clicked.connect(self.on_clicked)
self.tableWidget.setRowCount(10)
self.tableWidget.setColumnCount(4)
@QtCore.pyqtSlot(QtCore.QModelIndex)
def on_clicked(self, ix):
alternative_color = QtGui.QColor("salmon")
current_brush = ix.data(QtCore.Qt.BackgroundRole)
new_brush = (
QtGui.QBrush(alternative_color)
if current_brush in (None, QtGui.QBrush())
else QtGui.QBrush()
)
self.tableWidget.model().setData(ix, new_brush, QtCore.Qt.BackgroundRole)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
关于python - 更改 qtablewidget 中的颜色(单击),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59327964/