在使用cleanlooks风格时自定义QRubberBand外观
我想稍微调整一下我自定义的 QRubberBand
的外观。我希望能实现一个蓝色的选择边框,背景是透明的蓝色选择矩形。问题是,当我使用 CleanLooks 风格时,背景总是透明的,但如果我切换到比如 WindowsVista 风格,一切就正常了。
我在一台Windows电脑上使用的是 PyQt 10.4.3。
下面是一个小代码示例,你可以从中看到这种奇怪的行为。
from PyQt4 import QtGui,QtCore
from PyQt4.QtCore import Qt
class Selector(QtGui.QRubberBand):
"""
Custom QRubberBand
"""
def __init__(self,*arg,**kwargs):
super(Selector,self).__init__(*arg,**kwargs)
def paintEvent(self, QPaintEvent):
painter = QtGui.QPainter(self)
# set pen
painter.setPen(QtGui.QPen(Qt.blue,4))
# set brush
color = QtGui.QColor(Qt.blue)
painter.setBrush(QtGui.QBrush(color))
# set opacity
painter.setOpacity(0.3)
# draw rectangle
painter.drawRect(QPaintEvent.rect())
class Panel(QtGui.QWidget):
def __init__(self,parent = None):
super(Panel,self).__init__(parent)
self.rubberBand = Selector(QtGui.QRubberBand.Rectangle,self)
def mousePressEvent(self, QMouseEvent):
self.clickPosition = QMouseEvent.pos()
self.rubberBand.setGeometry(QtCore.QRect(self.clickPosition,QtCore.QSize()))
self.rubberBand.show()
def mouseMoveEvent(self, QMouseEvent):
pos = QMouseEvent.pos()
self.rubberBand.setGeometry(QtCore.QRect(self.clickPosition,pos).normalized())
def mouseReleaseEvent(self, QMouseEvent):
self.rubberBand.hide()
if __name__ == "__main__":
import sys
app = QtGui.QApplication([])
QtGui.QApplication.setStyle("cleanlooks")
pn = Panel()
pn.show()
sys.exit(app.exec_())
1 个回答
1
我在Qt中看到过其他图形界面元素有类似的表现(比如在这个问题里),我的感觉是Qt的样式设置有点复杂,可能会覆盖用户自己设置的样式。
原则上,你可以自己实现一个QStyle,把所有的样式设置放在里面。
不过,这里更简单的方法可能是把这个元素(这里是QRubberBand
)的样式设置成一个不会干扰的样式。
这样应该可以工作:
class Selector(QtGui.QRubberBand):
def __init__(self,*arg,**kwargs):
super().__init__(*arg,**kwargs)
self.setStyle(QtGui.QStyleFactory.create('windowsvista'))