我有一个包含窗口的应用程序。没有对默认样式进行任何修改。
我希望当我将鼠标悬停在表格中的特定项目上时,以数据提示样式出现 QLabel 无论我如何应用样式表,我都无法使标签的背景完全不透明。
特别是,当我使用以下几行时:
stylesheet = "QLabel{opacity:1; background: red; border: 1px solid white};"
label.setStyleSheet(window_stylesheet)
我得到的是这样的:
我在 OSX 上。如何使标签完全不透明?
编辑: 根据评论中的要求,这是一个显示标签创建方式的 MWE。
# hello.py
"""Simple Hello, World example with PyQt6."""
import sys
# 1. Import QApplication and all the required widgets
from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QTableWidget, QTableWidgetItem, QComboBox, QPushButton, QStyle, QStyleFactory
# hello.py
# ...
data = {
"col1": ['1', '2', '3', '4'],
"col2": ['1', '2', '3', '4'],
"col3": ['1', '2', '3', '4'],
"col4": ['1', '2', '3', '4']
}
class myTableView(QTableWidget):
def __init__(self, data, *args):
QTableWidget.__init__(self, *args)
self.data = data
self.setData(data)
self.resizeColumnsToContents()
self.resizeRowsToContents()
self.setAlternatingRowColors(True)
stylesheet = "QTableView:item{border-top: 1px solid rgba(255,255,255,0.2)}"
stylesheet_hovered = "QTableView:item:hover{background-color: rgba(255,255,255,0.3); border-top: 1px solid rgba(255,255,255,0.2)}"
self.setStyleSheet(stylesheet)
self.setStyleSheet(stylesheet_hovered)
self.setMouseTracking(True)
self.current_hover = [0, 0]
self.cellEntered.connect(self.cellHover)
def setData(self, data):
self.data = data
horHeaders = []
for n, key in enumerate(list(self.data.keys())):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)
self.resizeColumnsToContents()
self.resizeRowsToContents()
def cellHover(self, row, column):
item = self.item(row, column)
old_item = self.item(self.current_hover[0], self.current_hover[1])
infodict = {
x: self.data[x][row] for x in list(self.data.keys())
}
if self.current_hover != [row,column]:
if self.datatip.explaination_thread is not None:
self.datatip.cancelExplaination() # Cancel old datatip
self.datatip.showExplaination(infodict)
self.current_hover = [row, column]
class registerDataTip(QLabel):
def __init__(self, *args):
QTableWidget.__init__(self, *args)
self.setText('DATATIP')
self.explaination_thread = None
self.close()
def showExplaination(self, infodict):
self.setText(f'<b>{infodict["col1"]}</b><br>This is a test string<br>I should be opaque but I am not')
self.adjustSize()
# self.explaination_thread = setTimeout(1, self.show)
self.show()
def cancelExplaination(self):
self.close()
# self.show()
# 2. Create an instance of QApplication
app = QApplication([])
# 3. Create your application's GUI
window = QWidget()
window.setWindowTitle("PyQt App")
# window.setStyle(QStyleFactory.create('Fusion')) # won't work on windows style.
window.setGeometry(100, 100, 280, 80)
window_stylesheet = "QLabel{opacity:1; background: red; border: 1px solid white;};"
app.setStyleSheet(window_stylesheet)
#app.setStyleSheet(label_stylesheet)
table_meaning = myTableView(data, len(data[list(data.keys())[0]]), len(list(data.keys())), window)
label_meaning = registerDataTip(window)
label_meaning.move(800,500)
table_meaning.datatip = label_meaning
table_meaning.setGeometry(60, 100, 600, 800)
random_button = QPushButton(window)
random_button.move(800,500)
# 4. Show your application's GUI
window.showMaximized()
# 5. Run your application's event loop
sys.exit(app.exec())
结果:
标签是不透明的
问题是您正在为它设置相同的父项以及在它之后创建的按钮。因为它们共享同一个父级,last 创建的小部件总是显示在小部件堆栈的顶部。
创建按钮后只需添加以下行:
label_meaning.raise_()
请注意,您对“数据提示”的处理非常不正统,尤其是考虑到该小部件是由一个不相关的小部件管理的,并且管理不是其子对象的对象不应该是表的责任。更合适的解决方案是创建一个自定义信号,并将其连接到外部:
class MyTableView(QTableWidget):
showTip = pyqtSignal(dict)
# ...
def cellHover(self, row, column):
infodict = {
x: self.data[x][row] for x in list(self.data.keys())
}
if self.current_hover != [row,column]:
self.showTip.emit(infodict)
self.current_hover = [row, column]
class RegisterDataTip(QLabel):
# ...
def showExplaination(self, infodict):
if self.explaination_thread is not None:
self.cancelExplaination()
self.setText('''
<b>{}</b><br>
This is a test string<br>
I <b>am</b> opaque
'''.format(infodict["col1"]))
self.adjustSize()
self.show()
self.raise_()
# ...
table_meaning.showTip.connect(label_meaning.showExplaination)
注意CSS也有语法错误(最后一个分号)。也就是说,您关于不使用 QToolTip 的解释似乎不足以满足您的情况。只需阅读官方文档
(不是 PyQt 文档)。最后,请不要为类使用小写名称,这是一个糟糕的选择:类和常量应该 always 大写,以便轻松区分类/常量和函数/变量。