Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you change the color of the QT line widget in QT Designer

Tags:

qt

qt-designer

Kaveish offers a nice piece of code to work with on this How does designer create a Line widget? How would I change the color of those lines to blue from their black default color.

Thanks for any help

like image 446
E Purdy Avatar asked Oct 29 '22 08:10

E Purdy


1 Answers

There are a couple of different approaches for this, depending on your need. I'm going to post examples in Python, but porting to C++ is simple enough.

Set the QPalette

If you want to keep the look of the current style, you could try to set the palette colors. This works fine on Linux with the default Breeze and Oxygen styles:

palette = self.line.palette()
palette.setColor(palette.Window, QtGui.QColor(QtCore.Qt.lightGreen)
self.line.setPalette(palette)

Unfortunally not all theme/styles are implemented in the same way, and both the Windows and Fusion styles need to set the color for the palette.Dark role, which makes the whole solution very platform and style dependent, as an user could have his/her own styles installed.

Stylesheet

The stylesheet solution requires to implement the border properties of the QFrame widget subclass, but doesn't look always very good and it's better to setFixedHeight (or width for vertical lines) to 2 pixel maximum.

self.line.setStyleSheet('''
    MyLineClass {
        border: 0.5px solid green;
        border-style: inset;
    }
''')

QPaintEvent

Then there's the custom paint solution. This is a simple implementation that obtains an effect similar to the Oxygen "smooth" lines.

class MyHorizontalLine(QtWidgets.QWidget):
    grad = QtGui.QLinearGradient(0, 0, 1, 0)
    grad.setCoordinateMode(self.grad.StretchToDeviceMode)
    grad.setCoordinateMode(self.grad.ObjectBoundingMode)
    grad.setColorAt(0, QtGui.QColor(QtCore.Qt.transparent))
    grad.setColorAt(.5, QtGui.QColor(QtCore.Qt.darkGray))
    grad.setColorAt(1, QtGui.QColor(QtCore.Qt.transparent))
    gradPen = QtGui.QPen(QtGui.QBrush(grad), 1)

    def paintEvent(self, event):
        qp = QtGui.QPainter(self)
        qp.setRenderHints(qp.Antialiasing)
        qp.translate(.5, self.rect().center().y() - .5)
        qp.setPen(self.gradPen)
        qp.drawLine(0, 0, self.width(), 0)
        qp.translate(0, 1)
        qp.setOpacity(.5)
        qp.drawLine(0, 0, self.width(), 0)
like image 192
musicamante Avatar answered Nov 15 '22 05:11

musicamante