I want to draw some lines and points by PySide2 and I followed the documentations and provide code below, but it is not showing any thing after I call the function.
class Window2(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Deformed Structure")
self.DrawWindows = QtGui.QWindow()
self.DrawButton23 = QPushButton('Draw', self)
self.DrawButton23.setStyleSheet("Background-color: orange")
self.DrawButton23.move(100, 200)
self.DrawButton23.show()
self.DrawButton23.clicked.connect(self.PaintEvent)
def PaintEvent(self, painter):
painter = QtGui.QPainter()
painter.begin(self)
pen = QPen(Qt.green)
painter.setPen(pen)
for i in range(0, 10):
x0 = i * 30
y0 = i * 30
x1 = 100 + i * 50
y1 = 100 + i * 50
point1 = QPointF(x0, y0)
point2 = QPointF(x1, y1)
line1 = QLineF(point1, point2)
painter.drawPoint(point1)
painter.drawLine(line1)
print("OK123") #Just to check the loop, it prints 10 time
painter.end()
You must understand that:
Python and C++ are case sensitive so paintEvent is different from PaintEvent.
You should not invoke paintEvent directly but using the update() or repaint() method.
From what I understand is that you want the painting to be executed when you press the button but you cannot control the painting directly, the logic is to activate a certain part of the painting using some flag.
Considering the above, the solution is:
from PySide2 import QtCore, QtGui, QtWidgets
class Window2(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Deformed Structure")
self.flag = False
self.draw_button = QtWidgets.QPushButton("Draw", self)
self.draw_button.setStyleSheet("Background-color: orange")
self.draw_button.move(100, 200)
self.draw_button.clicked.connect(self.on_clicked)
def on_clicked(self):
self.flag = True
self.update()
def paintEvent(self, event):
painter = QtGui.QPainter(self)
if self.flag:
pen = QtGui.QPen(QtCore.Qt.green)
painter.setPen(pen)
for i in range(0, 10):
x0 = i * 30
y0 = i * 30
x1 = 100 + i * 50
y1 = 100 + i * 50
point1 = QtCore.QPointF(x0, y0)
point2 = QtCore.QPointF(x1, y1)
line1 = QtCore.QLineF(point1, point2)
painter.drawPoint(point1)
painter.drawLine(line1)
if __name__ == "__main__":
app = QtWidgets.QApplication()
w = Window2()
w.show()
app.exec_()