한국어
파이썬
 

PyQt4 [PyQt4]윈도우창에 별 찍기 예제

pjk 2014.08.19 19:44 조회 수 : 8130

K-20140819-708145.png

 

예제 소스코드

import sys
import math
import random
import sip

API_NAMES = ["QDate", "QDateTime", "QString","QTextStream", "QTime", "QUrl", "QVariant"]
API_VERSION = 2
for name in API_NAMES:
   sip.setapi(name, API_VERSION)

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Window(QWidget):

    def __init__(self, parent=None):

        QWidget.__init__(self, parent)

        self.thread = Worker()

        label = QLabel("Number of stars:")
        self.spinBox = QSpinBox()
        self.spinBox.setMaximum(10000)
        self.spinBox.setValue(100)
        self.startButton = QPushButton("&Start")
        self.viewer = QLabel()
        self.viewer.setFixedSize(300, 300)

        self.connect(self.thread, SIGNAL("finished()"), self.updateUi)
        self.connect(self.thread, SIGNAL("terminated()"), self.updateUi)
        self.connect(self.thread, SIGNAL("output(QRect, QImage)"), self.addImage)
        self.connect(self.startButton, SIGNAL("clicked()"), self.makePicture)

        layout = QGridLayout()
        layout.addWidget(label, 0, 0)
        layout.addWidget(self.spinBox, 0, 1)
        layout.addWidget(self.startButton, 0, 2)
        layout.addWidget(self.viewer, 1, 0, 1, 3)
        self.setLayout(layout)

        self.setWindowTitle("Simple Threading Example")

    def makePicture(self):

        self.spinBox.setReadOnly(True)
        self.startButton.setEnabled(False)
        pixmap = QPixmap(self.viewer.size())
        pixmap.fill(Qt.black)
        self.viewer.setPixmap(pixmap)
        self.thread.render(self.viewer.size(), self.spinBox.value())

    def addImage(self, rect, image):

        pixmap = self.viewer.pixmap()
        painter = QPainter()
        painter.begin(pixmap)
        painter.drawImage(rect, image)
        painter.end()
        self.viewer.update(rect)

    def updateUi(self):

        self.spinBox.setReadOnly(False)
        self.startButton.setEnabled(True)

class Worker(QThread):

    def __init__(self, parent=None):

        QThread.__init__(self, parent)
        self.exiting = False
        self.size = QSize(0, 0)
        self.stars = 0

        self.path = QPainterPath()
        angle = 2*math.pi/5
        self.outerRadius = 20
        self.innerRadius = 8
        self.path.moveTo(self.outerRadius, 0)
        for step in range(1, 6):
            self.path.lineTo(
                self.innerRadius * math.cos((step - 0.5) * angle),
                self.innerRadius * math.sin((step - 0.5) * angle)
                )
            self.path.lineTo(
                self.outerRadius * math.cos(step * angle),
                self.outerRadius * math.sin(step * angle)
                )
        self.path.closeSubpath()

    def __del__(self):

        self.exiting = True
        self.wait()

    def render(self, size, stars):

        self.size = size
        self.stars = stars
        self.start()

    def run(self):

        # Note: This is never called directly. It is called by Qt once the
        # thread environment has been set up.

        random.seed()
        n = self.stars
        width = self.size.width()
        height = self.size.height()

        while not self.exiting and n > 0:

            image = QImage(self.outerRadius * 2, self.outerRadius * 2,
                           QImage.Format_ARGB32)
            image.fill(qRgba(0, 0, 0, 0))

            x = random.randrange(0, width)
            y = random.randrange(0, height)
            angle = random.randrange(0, 360)
            red = random.randrange(0, 256)
            green = random.randrange(0, 256)
            blue = random.randrange(0, 256)
            alpha = random.randrange(0, 256)

            painter = QPainter()
            painter.begin(image)
            painter.setRenderHint(QPainter.Antialiasing)
            painter.setPen(Qt.NoPen)
            painter.setBrush(QColor(red, green, blue, alpha))
            painter.translate(self.outerRadius, self.outerRadius)
            painter.rotate(angle)
            painter.drawPath(self.path)
            painter.end()

            self.emit(SIGNAL("output(QRect, QImage)"),
                      QRect(x - self.outerRadius, y - self.outerRadius,
                            self.outerRadius * 2, self.outerRadius * 2), image)
            n -= 1

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    app.exec_()

 

번호 제목 글쓴이 날짜 조회 수
24 외부 프로그램 실행 pjk 2015.02.10 15253
23 [PyQt4]여러가지 버튼 예제 file pjk 2014.08.29 13678
22 [PyQt4]폴더 또는 파일을 드레그하여 그 경로를 LineEdit로 가져오기 file pjk 2014.08.22 13508
21 [pyqt4]QTimer 예제 - 버튼을 누르면 3초후 함수 또는 메소드 호출 makersweb 2015.04.01 9596
20 Boost Python을 이용하여 python을 위한 C++ API 바인딩 [5] file makersweb 2017.01.08 9019
19 [Python]EXE또는 DLL파일의 버전정보를 알아내기위한 몇가지 방법 makersweb 2015.06.25 8633
18 [PyQt4]스레드 및 ProgressBar 예제 코드 file pjk 2014.08.26 8236
17 [PyQt4]multiprocess 예제 코드 pjk 2014.08.26 8136
» [PyQt4]윈도우창에 별 찍기 예제 file pjk 2014.08.19 8130
15 Python으로 작성된 프로그램을 윈도우응용프로그램(exe)으로 빌드하기 file pjk 2014.08.03 8090
14 Python + QML with PyQt4 makersweb 2015.03.24 7850
13 [PyQt4]개발 프로그램 버전표시 메세지 박스 pjk 2014.09.02 7640
12 파이썬으로 작성된 소스를 py2exe을 이용하여 윈도우 응용프로그램 빌드시 콘솔창 숨기기 pjk 2014.07.29 7590
11 [PyQt4]마우스 클릭 이벤트 예제 코드 pjk 2014.08.26 6770
10 Python 문자열 관련 함수 레퍼런스 pjk 2014.08.29 6574
9 print를 로그파일로 생성하기 (log출력 Redirection) makersweb 2015.03.18 5471
8 Qt For Python(PySide2) QML 프로젝트 예제 file makersweb 2019.10.17 4751
7 How to Use Freeze pjk 2014.09.06 4707
6 다른 디렉터리의 파일(모듈) import 하기 pjk 2014.08.22 4691
5 QML 및 Window 투명처리 file makersweb 2015.04.22 3983