在qtablewidget中更改颜色(单击)

时间:2019-12-13 18:23:47

标签: python pyqt pyqt5

帮助实现代码,以便在单击表中的单元格时,小部件单元格会更改其颜色,再次单击时,它会再次变为白色

我正在尝试实现文件管理器。

代码:

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)

1 个答案:

答案 0 :(得分:1)

您必须切换与每个元素的Qt :: BackgroundRole函数关联的QBrush。您可以使用itemClicked,但这可能会失败,因为并非QTableWidget中的所有项目都具有关联的QTableWidgetItem,因此最好使用关联的QModelIndex返回的clicked信号

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_())
相关问题