python - 更改 qtablewidget 中的颜色(单击)

标签 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)

最佳答案

您必须切换与每个元素的 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/

相关文章:

python - 运行带有 pm2 错误的 python 脚本

python - 匹配某个词之后的字符,停止匹配这个同一个词之前的字符

python - QFileDialog 作为 TableView 的编辑器 : how to get result?

Python PyQt QtoolbuttonPopup 模式

python - 创建一个小部件嵌入到 QMainWindow 中

python - 从 txt 文件中删除重复的行

python - 在 python 中拟合泊松直方图的问题

python - QSound 在对象内部的意外行为

python - 如何迭代使用 QStandardItemModel 创建的动态创建的复选框列表?

javascript - 如何使用pyqt5获取网页?