现在,正如您在下面的图2中看到的,当选择第一行时,所有文本的颜色都设置为黑色,而不是保持其原始样式显示在图1上。
有没有办法在选择行时保留原始颜色(如图图3所示)?我应该继续单独依赖 CSS 还是应该创建一个
QAbstractItemDelegate
来解决这个问题?
如果需要
QAbstractItemDelegate
,它比使用 CSS 更快还是会减慢应用程序速度?
图1:没有任何选择的情况下的样子。
图 2:用户选择第 0 行时的样子。
图 3:在 Paint 上制作,我希望它的表现如何。
设置:
我正在 Windows 10 上的 Python 3.10 上使用 PySide2:Qt5。
在我的示例中,在向其中插入行之前,我在
QTableWidget
上设置了一些属性:
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setDragDropMode(QAbstractItemView.NoDragDrop)
self.setFocusPolicy(Qt.NoFocus)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setAlternatingRowColors(True)
self.setShowGrid(False)
tv = self.verticalHeader()
tv.setVisible(False)
tv.setSectionsClickable(False)
tv.setSectionResizeMode(QHeaderView.Fixed)
tv.setDefaultAlignment(Qt.AlignHCenter)
th = self.horizontalHeader()
th.setHighlightSections(False)
th.setStretchLastSection(True)
th.setSectionResizeMode(QHeaderView.Interactive)
# With Exception to Column 0: ResizeMode is ResizeToContents
然后我创建了一个函数来轻松地在其中插入项目。这是一个很大的函数,它依赖于
QTableWidget
和 QTableWidgetItem
中的一些方法,如下所示:
# Insert the row at the table, on specified index
self.insertRow(index)
# Get the QTableWidgetItem from row r and column c, and ensure it exists
item = self.item(r, c)
if (item is None):
item = QTableWidgetItem()
self.setItem(r, c, item)
# To change the text color, using a QColor
QTableWidgetItem.setForeground()
# To change the text alignment, using Qt Flags
QTableWidgetItem.setTextAlignment()
# To set the text inside the cell
QTableWidgetItem.setText()
与这些小部件相关的我的 CSS 是:
QTableWidget {
border: 1px solid #ddd;
}
QTableWidget::item {
background-color: white;
}
QTableWidget::item:alternate {
background-color: #f1f1f1;
}
/* I Have already tried setting 'color: inherit', but there is no effect */
QTableView::item:selected, QTableView::item:alternate:selected {
background-color: #92b7d1;
}
QHeaderView::section {
background-color: lightgray;
}
QHeaderView::section:hover {
background-color: silver;
}
发帖后忘记提及:“颜色”列上的圆形彩色方块是来自 FontAwesomes 的 Unicode 文本,我下载了 OTF 文件并使用 PySide2 中的
QFontDatabase
添加到应用程序中。基本上就是这个人这里。
对于仍然想知道的人,大约一年后,我发现存在一个 module 可以将 FontAwesome(和其他来源)图标转换为 QIcons 甚至 QWidgets。
使用该模块,您可以指定颜色参数并在创建过程中随意更改图标的颜色。比我在这篇文章中所做的一切要容易得多。
如果您正在阅读这篇文章,我建议您查看一下。