Python Qt bindings: how to increase line width with 0 width
With the following simple example (which works well with PySide or PyQt4 on my computer):
import sys
import random
import numpy
from PySide import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.resize(800, 500)
self.view = QtGui.QGraphicsView()
self.scene = QtGui.QGraphicsScene()
self.view.setScene(self.scene)
self.setWindowTitle('Example')
# Layout
layout = QtGui.QGridLayout()
layout.addWidget(self.view, 0, 0)
self.setLayout(layout)
# Styles
self.pen = QtGui.QPen(QtCore.Qt.black, 0, QtCore.Qt.SolidLine)
self.brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 255))
def addLine(self, x0, y0, x1, y1):
line = QtCore.QLineF(x0, -y0, x1, -y1)
pen = QtGui.QPen(QtGui.QColor(250, 0, 0, 255), 0, QtCore.Qt.SolidLine)
pen.setStyle(QtCore.Qt.CustomDashLine)
pen.setDashPattern([1, 4, 5, 4])
l = self.scene.addLine(line, pen)
def addRect(self, left, top, width, height):
rect = QtCore.QRectF(left, -top, width, abs(height))
r = self.scene.addRect(rect, self.pen, self.brush)
def fit(self):
self.view.fitInView(self.scene.sceneRect())
def resizeEvent(self, event = None):
self.fit()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
window.addRect(0, 1, 1, 1)
window.addLine(-1, -1, 2, 2)
window.addLine(0, 1, 1, 0)
window.fit()
sys.exit(app.exec_())
I can draw two red lines that are of constant width; which means they don't change, doesn't matter the size (coordinates) of the square and lines, and doesn't matter if I resize the window:
This is because I am using QtGui.Qpen
with width 0
. However, if I use a different width > 0
, then the observed line width changes to the window size (or changes if the square and lines are also different sizes):
Is it possible to change the line width so that the observed lines are thicker than those obtained when the width is set to 0
, while maintaining the same "observed" width when the window is resized or when the square / line is resized?
EDIT
Using setCosmetic(True)
as suggested by o11c has unexpected behavior (at least I didn't expect this to happen); it adds margins to the image (increases size scene.sceneRect()
). These margins appear to be proportional to the width QPen
when isCosmetic() == True
:
A new question has been created related to this issue. See question 26231374 for more details :
source to share
According to the Qt C ++ documentation, use a setCosmetic
function in QPen
. I assume the python shell provides this.
source to share