开启Qt.WA_TranslucentBackground时QLineEdit聚焦高亮消除方案
问题原因
你遇到的聚焦透明高亮问题是Mac平台下Qt默认继承系统控件样式导致的:你仅关闭了WA_MacShowFocusRect属性,但没有覆盖QLineEdit的选中态背景、聚焦伪状态默认样式,系统默认的半透明选中背景会透出窗口后方的内容,光标默认半透效果也会出现同样的问题。
解决方案
1. 补充QLineEdit样式表配置
你需要在原有样式表基础上补充选中态、光标、聚焦伪状态的样式配置,示例如下:
QLineEdit{ background:transparent; outline: none; border: none; color: white; /* 自定义文本显示颜色 */ caret-color: white; /* 自定义光标颜色,解决光标透明透背景问题 */ selection-background-color: #606060; /* 自定义选中高亮颜色,和窗口背景适配即可避免透出后方内容,要完全消除高亮可设为transparent */ selection-color: white; /* 自定义选中状态下的文本颜色 */ } QLineEdit:focus{ border: none; outline: none; background: transparent; }
2. 额外添加控件属性
在TransparentLineEdit的__init__方法中补充一行属性设置,关闭系统默认背景绘制:
self.setAttribute(Qt.WA_NoSystemBackground, True)
修改后完整可运行代码
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QWidget, QLineEdit, QApplication, QVBoxLayout, QLabel from PyQt5.QtGui import QPainter, QFont, QBrush class TransparentLineEdit(QLineEdit): def __init__(self, parent=None): super(TransparentLineEdit, self).__init__(parent) font = QFont() font.setFamily('Helvetica Neue') font.setWeight(10) font.setPointSize(32) self.setFont(font) self.setAttribute(Qt.WA_MacShowFocusRect, False) self.setAttribute(Qt.WA_NoSystemBackground, True) self.setStyleSheet(""" QLineEdit{ background:transparent; outline: none; border: none; color: white; caret-color: white; selection-background-color: #606060; selection-color: white; } QLineEdit:focus{ border: none; outline: none; background: transparent; } """) class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # window style winwidth = 400 winheight = 120 # 原高度太窄放不下QLabel+输入框,调整了高度 self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint ) self.setAttribute(Qt.WA_TranslucentBackground, True) self.setGeometry(0, 0, winwidth, winheight) pos = QApplication.desktop().screen().rect().center()-self.rect().center() pos.setY(pos.y() - 100) self.move(pos) # window contents MainLayout = QVBoxLayout() MainLayout.setContentsMargins(10, 10, 10, 10) InputField = TransparentLineEdit() MainLayout.addWidget(QLabel('INPUT')) MainLayout.addWidget(InputField) self.setLayout(MainLayout) def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QBrush(Qt.darkGray)) painter.setPen(Qt.transparent) bgrect = event.rect() bgrect.setWidth(bgrect.width() -1) bgrect.setHeight(bgrect.height() -1) painter.drawRoundedRect (bgrect, 5, 5) painter.end() if __name__ == '__main__': import sys app = QApplication(sys.argv) win = MainWindow() win.show() sys.exit(app.exec_())
注:如果你不需要显示选中高亮,直接把
selection-background-color设为transparent即可完全消除选中高亮效果。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

