3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python3とPyQt5を使ってのGUIプログラミング(2)~描画~

Last updated at Posted at 2016-08-06

前回
##描画
QWidgetに描画するためにはpaintEventメソッドをオーバーライドします
drawRectで矩形を描画します

    def paintEvent(self, QPaintEvent):
        painter = QPainter(self)
        painter.setPen(Qt.black)
        painter.setBrush(Qt.red)
        painter.drawRect(10, 10, 10, 10)# x座標、y座標、高さ、幅

##更新

更新するためにはupdateメソッドを呼びます

self.update()

定期的に更新したい場合はQtのタイマーを使う

self.timer = QTimer(self)
self.timer.timeout.connect(self.update)
self.timer.start(1000)#ミリ秒単位

##例

test.py

# coding: UTF-8

import sys
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QLabel, QWidget
from PyQt5.QtGui import QPainter, QFont
from PyQt5.QtCore import Qt, QTimer


class Test(QWidget):

    def __init__(self):
        app = QApplication(sys.argv)

        super().__init__()
        self.init_ui()
        self.show()

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update)
        self.timer.start(1000)#一秒間隔で更新

        app.exec_()

    def init_ui(self):
        self.setWindowTitle("PyQt5")
        self.resize(640, 400)
        self.frameGeometry()\
            .moveCenter(
                        QDesktopWidget()
                        .availableGeometry()
                        .center()
                        )
        self.x = 0
        self.y =200

    def paintEvent(self, QPaintEvent):
        painter = QPainter(self)
        painter.setPen(Qt.black)
        painter.setBrush(Qt.red)

        self.x += 1
        if self.x > 640:
            self.x = 0

        painter.drawRect(self.x, self.y, 10, 10)


if __name__ == '__main__':
    Test()

すごくゆっくりですが赤い四角が右に動いていくはずです
timerでupdateを呼ぶ間隔を短くすればもっと早くなります

間違い等がありましたらコメントで教えて下さい

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?