PyQt5:chapter10-さまざまなグラフィカルツールを表示するツールバーを作成します

インスタンス

  1. メインウィンドウテンプレートに基づいてウィンドウを作成します
  2. 右クリックしてメニューバーを削除します
  3. アクションエディタでアクションを編集し、円、長方形、線のアクションを作成します
  4. アイコンアイコンの追加既存のファイルを選択するか、新しい.qrcファイルを作成し、右側に.icoアイコンを追加します
  5. メインウィンドウを右クリックしてツールバーTooBarを追加し、編集したアクションをツールバーにドラッグします
  6. demoToolBars.uiとして保存
  7. pyuicを使用してdemoToolBars.pyを生成します
  8. callToolBars.pyを作成します
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QPainter
from cookbook_200505.demoToolBars import *
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.pos1 = [0,0]
        self.pos2 = [0,0]
        self.toDraw=""
        self.ui.actionCircle.triggered.connect(self.drawCircle)
        self.ui.actionRectangle.triggered.connect(self.drawRectangle)
        self.ui.actionLine.triggered.connect(self.drawLine)
        self.show()
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        if self.toDraw=="rectangle":
            width = self.pos2[0]-self.pos1[0]
            height = self.pos2[1] - self.pos1[1]
            qp.drawRect(self.pos1[0], self.pos1[1], width, height)
        if self.toDraw=="line":
            qp.drawLine(self.pos1[0], self.pos1[1],self.pos2[0], self.pos2[1])
        if self.toDraw=="circle":
            width = self.pos2[0]-self.pos1[0]
            height = self.pos2[1] - self.pos1[1]
            rect = QtCore.QRect(self.pos1[0], self.pos1[1],width, height)
            startAngle = 0
            arcLength = 360 *16
            qp.drawArc(rect, startAngle, arcLength)
            qp.end()
    def mousePressEvent(self, event):
        if event.buttons() & QtCore.Qt.LeftButton:
            self.pos1[0], self.pos1[1] = event.pos().x(),event.pos().y()
    def mouseReleaseEvent(self, event):
        self.pos2[0], self.pos2[1] = event.pos().x(),event.pos().y()
        self.update()
    def drawCircle(self):
        self.toDraw="circle"
    def drawRectangle(self):
        self.toDraw="rectangle"
    def drawLine(self):
        self.toDraw="line"
if __name__=="__main__":
    app = QApplication(sys.argv)
    w = AppWindow()
    w.show()
    sys.exit(app.exec())

おすすめ

転載: blog.csdn.net/weixin_43307431/article/details/105982184