* pyqtgraph 내려받기

 

* 예제 소스 (극곡선 r = 2 cos(3 theta) 그리기)

# -*- coding: utf-8 -*-

# Filename: testPyQtGraph_03.py
# Execute: python testPyQtGraph_03.py


from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

app = QtGui.QApplication([])

win = pg.GraphicsWindow(title="Basic plotting examples")

win.resize(400, 500)
win.setWindowTitle('pyqtgraph example: Plotting')

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

p1 = win.addPlot(title="Parametric, grid enabled")
a = 2.0
k = 3.0
theta = np.linspace(0, 2*np.pi, 1000)
x = a*np.cos(theta)*np.cos(k*theta)
y = a*np.sin(theta)*np.cos(k*theta)
p1.plot(x, y)
p1.showGrid(x=True, y=True)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

 

* 실행 결과:

 

 

더 많은 pyqtgraph 예제:

프롬프트> cd %PYTHON27_HOME%\\Lib\site-packages\pyqtgraph

프롬프트> python -m examples

 

 

 

Posted by Scripter
,

* Qt 5.2.1 내려받기  (아래의 예는 Visual Studio 2010 용을 받아서 설치한 경우이다. Qt Creator 3.0.1 은 자동으로 함께 설치된다,)

 

Qt Creator 를 시작한 후 메뉴에서

         File --> New File or Project...

를 택한다. 그리고 New 창에서 다음 그림에서와 같이

        Applications --> Qt Quick Application

을 택하고 "Choose..." 버튼을 클릭한다.

 

이어 나타나는 New Qt qUICK aPPLICATION 창에서 애플리케이션이 생성될 폴더와 이름을 정한다. 원하는 폴더거 없는 경우 그 우측의 "Browse" 버튼을 클릭하여 생성하거나 선택한다.

 

다음 창에서는 Qt Quick Componenet Set 을 정한다. Qt 5.0 이상은 "Qt Quick 2.0" 으ㅜㄹ 택한다.

 

다음 창에서는 Kit Selection 을 설정한다. (이 예에서는 Visual C 2010 용으로 설치한 경우이다.)

 

다음 창에서는 Project Management 를 확인한다. 앞으로 main.qml 파일만 수정하고 저장한 후 실행하면 된다. (실행 버튼만 누르면 빌드는 저절로 된다.)

 

 

* main.cpp 의 내용 (자동으로 생성된 후 수정되지 않음)

 

#include <QtGui/QGuiApplication>

#include "qtquick2applicationviewer.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/ThirdHelloQtQuickApp/main.qml"));
    viewer.showExpanded();

    return app.exec();
}
 

 

* main.qml 의 내용 (자동 생성된 main.qml 파일의 내용을 아래 처럼 수정한다.)

import QtQuick 2.0

Rectangle {
    id: page
    width: 320; height: 160
    color: "lightgray"

    Text {
        id: helloText
        text: "Hello, world!<br /><br />안녕하세요?"
        y: 25
        anchors.horizontalCenter: page.horizontalCenter
        font.pointSize: 24; font.bold: true; font.italic: true
    }
}

 

 

* Releae/Debug 변경하기 그리고 실행하기 (Qt Creator 창의 좌측 아래 부분)

 

 

* Release 배포를 위해 PATH 에 지정된 폴더에 꼭 있어야 하는 파일들:

icudt51.dll
icuin51.dll
icuuc51.dll
libEGL.dll
libGLESv2.dll
Qt5Core.dll
Qt5Gui.dll
Qt5Network.dll
Qt5Qml.dll
Qt5Quick.dll
ThirdHelloQtQuickApp.exe
 
 

 

* 만일 PATH 로 지정된 경로에 libEGL.dll 이 없으면 다음 에러 메시지 창이 뜬다.

 

 

 

* 실행 결과:

 

 

 

 

 

Posted by Scripter
,

** PySide 설치하기

** QtDesigner 내려받기

** 윈도우즈 용 git 를 설치하기

 

* 다음 소스는 http://qt-project.org/wiki/PySideSimplicissimus_Module_2_CloseButton 에서 볼 수 있는 소스이다.

 

#!/usr/bin/env python

# quitter.py - provide a button to quit this "program"

import sys

from PySide.QtGui import QMainWindow, QPushButton, QApplication
from ui_quitter import Ui_MainWindow

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    frame = MainWindow()
    frame.show()   
    app.exec_()

 

프롬프트> python quitter.py
Traceback (most recent call last):
  File "quitter.py", line 8, in <module>
    from ui_quitter import Ui_MainWindow
ImportError: No module named ui_quitter

ui_quitter 모듈이 없다는 에러 메시지이다.

 

* quitter.ui 를 구하기 위한  tuts4pyside 를 내려 받기 (quiter.ui 파일은 QtDesigner 를 이용하여 만든 파일이다.)

프롬프트> git clone https://github.com/OldAl/tuts4pyside

 

* quitter.ui 복사하기 (quittere,ui 파일을 현재 폴더에 복사한다.)

프롬프트> copy .\tuts4pyside\quit_prog\quitter.ui

* quitter.ui 로 부터 ui_quitter.py 를 생성하기 (실행 파일 pyside_uic.exe 는 C:\Python27\Scripts 폴더에 존재한다.)

프롬프트> c:\python27\scripts\pyside-uic quitter.ui -o ui_quitter.py

 

* 실행하기

프롬프트> python quitter.py

 

 

 

 

Posted by Scripter
,

전개 공식

        (ax + b)(cx + d) = acx^2 + (ad + bc)x + bd

에 기반을 둔 쉬운 곱셉법(일명 카라슈바 곱셈법)이다.

여기서 특히 a == b or a == c or b == d or c == d 인 경우이면

      ad + bc = s(c + d)  or ad + bc = a(b + d)

      or ad + bc = b(s + c) or ad + bc = c(a + b)

로 더 쉬운 곱셈 계산이 가능하다.

 

#!/usr/bin/python
# -*- coding: utf-8 -*-


# Filename: ezMult_02.py
#
# Execute: python ezMult_02.py
#
# See: http://zetcode.com/gui/pyqt4/widgets2/
# See: http://zetcode.com/gui/pyqt4/


import sys
import sys, random
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
   
    def __init__(self):
        super(Example, self).__init__()
       
        self.ngame = 1
        self.npoint = 0
        self.doneflag = False
       
        self.initUI()
       
    def initUI(self):
        self.rect = QtCore.QRect(0, 30, 300, 220)
        self.xa = random.randint(11, 99)
        self.ya = random.randint(11, 99)
        self.lblXA = QtGui.QLabel(self)
        self.lblYA = QtGui.QLabel(self)
        self.lblYA.setFont(QtGui.QFont('Decorative', 16))
        self.lblXA.setFont(QtGui.QFont('Decorative', 16))
        self.lblXA.setText(str(self.xa))
        self.lblYA.setText(str(self.ya))
        self.lblXA.move(80, 60)
        self.lblYA.move(80, 80)

        self.lblAA = QtGui.QLabel(self)
        self.lblAA.setFont(QtGui.QFont('Decorative', 16))
        self.lblAA.setText("")
        self.lblAA.move(65, 90)

        self.lblBA = QtGui.QLabel(self)
        self.lblBA.setFont(QtGui.QFont('Decorative', 16))
        self.lblBA.setText("")
        self.lblBA.move(105, 110)

        self.lblCA = QtGui.QLabel(self)
        self.lblCA.setFont(QtGui.QFont('Decorative', 16))
        self.lblCA.setText("")
        self.lblCA.move(105, 120)

        self.lblOpa = QtGui.QLabel(self)
        self.lblOpa.setFont(QtGui.QFont('Decorative', 16))
        self.lblOpa.setText("X")
        self.lblOpa.move(40, 80)


        self.x = random.randint(11, 99)
        self.y = random.randint(11, 99)
        self.lblX = QtGui.QLabel(self)
        self.lblY = QtGui.QLabel(self)
        self.lblX.setText(str(self.x))
        self.lblY.setText(str(self.y))
        self.lblX.move(160, 40)
        self.lblY.move(160, 60)
        self.lblOp = QtGui.QLabel(self)
        self.lblOp.setText("X")
        self.lblOp.move(120, 60)
       
       
        self.lbl = QtGui.QLabel(self)
        self.lbl.move(60, 40)
        self.lbl.setHidden(True)

        self.lblScore = QtGui.QLabel(self)
        self.lblScore.setText("Score:")
        self.lblScore.move(10, 10)

        self.lblMsg = QtGui.QLabel(self)
        self.lblMsg.setText("Your first game")
        self.lblMsg.move(10, 255)

        self.lblScore.setFont(QtGui.QFont('Times New Roman', 12))
        self.lblMsg.setFont(QtGui.QFont('Times New Roman', 12))
       
       
        self.qleA = QtGui.QLineEdit(self)
        self.qleA.setFont(QtGui.QFont('Decorative', 20))
        self.qleA.setMaxLength(4)

        self.qleA.move(165, 90)
        self.qleA.resize(80, 30)

        self.qleB = QtGui.QLineEdit(self)
        self.qleB.setFont(QtGui.QFont('Decorative', 20))
        self.qleB.setMaxLength(3)
       
        self.qleB.move(165, 125)
        self.qleB.resize(60, 30)

        self.qleC = QtGui.QLineEdit(self)
        self.qleC.setFont(QtGui.QFont('Decorative', 20))
        self.qleC.setMaxLength(4)
       
        self.qleC.move(165, 170)
        self.qleC.resize(80, 30)

        if self.isSimple(self.xa, self.ya):
            self.redrawSimpleSubTable()
        else:
            self.redrawSubTable()
           
        if self.isSimple(self.x, self.y):
            self.redrawSimpleTable()
        else:
            self.redrawTable()
           
        self.btnExit = QtGui.QPushButton('Exit', self)
        self.btnExit.move(310, 60)
        self.btnExit.clicked.connect(self.doExit)
        self.btnExit.setEnabled(False)    

        self.btnMore = QtGui.QPushButton('More', self)
        self.btnMore.move(310, 120)
        self.btnMore.clicked.connect(self.moreGame)
        self.btnMore.setEnabled(False)  

        self.btnConfirm = QtGui.QPushButton('Ok', self)
        self.btnConfirm.move(310, 180)
        self.btnConfirm.clicked.connect(self.scoreGame)

        self.btnExit.setFont(QtGui.QFont('Arial', 12))
        self.btnMore.setFont(QtGui.QFont('Arial', 12))
        self.btnConfirm.setFont(QtGui.QFont('Arial', 12))


        self.qleA.textChanged[str].connect(self.onChanged)
       
        self.setGeometry(300, 300, 420, 280)
        self.setWindowTitle('Training Tool for Easy Multiplication')
        self.show()


    def moreGame(self):  
        self.update(self.rect)
          
        self.xa = random.randint(11, 99)
        self.ya = random.randint(11, 99)
        self.lblXA.setText(str(self.xa))
        self.lblYA.setText(str(self.ya))
       
        self.x = random.randint(11, 99)
        self.y = random.randint(11, 99)
        self.lblX.setText(str(self.x))
        self.lblY.setText(str(self.y))
       
        self.qleA.setText("")
        self.qleB.setText("")
        self.qleC.setText("")
       
        if self.isSimple(self.xa, self.ya):
            self.redrawSimpleSubTable()
        else:
            self.redrawSubTable()
           
        if self.isSimple(self.x, self.y):
            self.redrawSimpleTable()
        else:
            self.redrawTable()

        self.show()
        self.qleA.setFocus(True)    # See: http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html
        self.btnMore.setEnabled(False)  
        self.btnConfirm.setEnabled(True) 

        if self.ngame == 1:
            self.lblMsg.setText("Your first game")
        elif self.ngame == 2:
            self.lblMsg.setText("Your second game")
        elif self.ngame == 3:
            self.lblMsg.setText("Your third game")
        elif self.ngame == 4:
            self.lblMsg.setText("Your fourth game")
        elif self.ngame == 5:
            self.lblMsg.setText("Your fFifh game")
        else:
            self.lblMsg.setText("Your %d-th game" % self.ngame)
        self.lblMsg.adjustSize()


    def scoreGame(self):
        c = int(self.qleC.text())
       
        if self.isSimple(self.x, self.y):
            if c == self.x*self.y:
                 self.npoint += 1
                 self.lblMsg.setText("Right!")
                 if self.npoint == 5 and self.npoint == self.ngame:
                     self.lblMsg.setText("Congratulation!!")
                 self.lblMsg.adjustSize()
            else:
                s3 = "%d -> %d" % (c,  self.x*self.y)
                self.lblMsg.setText("Wrong! (%s)" % s3)
                self.lblMsg.adjustSize()
        else:
            a = int(self.qleA.text())
            b = int(self.qleB.text())
            if a == int(self.x / 10)*int(self.y / 10)*100 + (self.x % 10)*(self.y % 10) and \
                         b == int(self.x / 10)*(self.y % 10) + (self.x % 10)*int(self.y / 10) and \
                         c == self.x*self.y:
                 self.npoint += 1
                 self.lblMsg.setText("Right!")
                 if self.npoint == 5 and self.npoint == self.ngame:
                     self.lblMsg.setText("Congratulation!!")
                 self.lblMsg.adjustSize()
            else:
                s1 = ""
                if a != int(self.x / 10)*int(self.y / 10)*100 + (self.x % 10)*(self.y % 10):
                    s1 = "%d -> %d" % (a,  int(self.x / 10)*int(self.y / 10)*100 + (self.x % 10)*(self.y % 10))
                s2 = ""
                if b !=int(self.x / 10)*(self.y % 10) + (self.x % 10)*int(self.y / 10):
                    if len(s1) > 0:
                        s2 = ", "
                    s2 += "%d -> %d" % (b, int(self.x / 10)*(self.y % 10) + (self.x % 10)*int(self.y / 10))
                s3 = ""
                if c != self.x*self.y:
                    if len(s2) > 0:
                        s3 = ", "
                    s3 += "%d -> %d" % (c,  self.x*self.y)
                self.lblMsg.setText("Wrong! (%s%s%s)" % (s1, s2, s3))
                self.lblMsg.adjustSize()
       
        self.lblScore.setText("Your current score is %d in %d tries," % (20*self.npoint, self.ngame))
        self.lblScore.adjustSize()

        self.ngame += 1

        if self.ngame <= 5:
            self.btnMore.setEnabled(True)   
            self.btnMore.setFocus(True)    
        else:
            self.btnExit.setEnabled(True)  
            self.btnExit.setFocus(True)  
            self.btnMore.setEnabled(False)    
        self.btnConfirm.setEnabled(False)   


    def isSimple(self, x, y):
        if int(x/10) == int(y/10) or x % 10 == y % 10    \
                    or int(x/10) == x % 10 or int(y/10) == y % 10:
            return True
        else:
            return False


    def redrawSimpleSubTable(self):
        self.lblAA.setHidden(True)
        self.lblBA.setHidden(True)
        ca = int(self.xa) * int(self.ya)
        if len(str(ca)) == 3:
            self.lblCA.setText(str(ca))
            self.lblCA.move(72, 109)
            self.lblCA.adjustSize()
        else:
            self.lblCA.setText(str(ca))
            self.lblCA.move(60, 109)
            self.lblCA.adjustSize()


    def redrawSimpleTable(self):
        self.qleA.setHidden(True)
        self.qleB.setHidden(True)
        c = int(self.x) * int(self.y)
        if len(str(c)) == 3:
            self.qleC.setMaxLength(3)
            self.qleC.move(213, 110)
            self.qleC.resize(60, 30)
        else:
            self.qleC.setMaxLength(4)
            self.qleC.move(195, 110)
            self.qleC.resize(80, 30)


    def redrawSubTable(self):
        self.lblAA.setHidden(False)
        self.lblBA.setHidden(False)
        aa = int(self.xa/10) * int(self.ya / 10) * 100 + (self.xa % 10) * (self.ya % 10)
        if len(str(aa)) == 3:
            self.lblAA.setText(str(aa))
            self.lblAA.move(72, 109)
            self.lblAA.adjustSize()
        else:
            self.lblAA.setText(str(aa))
            self.lblAA.move(60, 109)
            self.lblAA.adjustSize()

        ba = int(self.xa % 10) * int(self.ya / 10) +  int(self.xa / 10) * int(self.ya %10)
        if len(str(ba)) == 1:
             self.lblBA.setText(str(ba))
             self.lblBA.move(84, 133)
             self.lblBA.adjustSize()
        elif len(str(ba)) == 2:
             self.lblBA.setText(str(ba))
             self.lblBA.move(72, 133)
             self.lblBA.adjustSize()
        else:
             self.lblBA.setText(str(ba))
             self.lblBA.move(60, 133)
             self.lblBA.adjustSize()

        ca = int(self.xa) * int(self.ya)
        if len(str(ca)) == 3:
             self.lblCA.setText(str(ca))
             self.lblCA.move(72, 164)
             self.lblCA.adjustSize()
        else:
             self.lblCA.setText(str(ca))
             self.lblCA.move(60, 164)
             self.lblCA.adjustSize()


    def redrawTable(self):
        self.qleA.setHidden(False)
        self.qleB.setHidden(False)
        a = int(self.x/10) * int(self.y / 10)
        if len(str(a)) == 1:
            self.qleA.setMaxLength(3)
            self.qleA.move(213, 110)
            self.qleA.resize(60, 30)
        else:
            self.qleA.setMaxLength(4)
            self.qleA.move(195, 110)
            self.qleA.resize(80, 30)

        b = int(self.x % 10) * int(self.y / 10) +  int(self.x / 10) * int(self.y %10)
        if len(str(b)) == 1:
             self.qleB.setMaxLength(1)
             self.qleB.move(235, 145)
             self.qleB.resize(20, 30)
        elif len(str(b)) == 2:
             self.qleB.setMaxLength(2)
             self.qleB.move(213, 145)
             self.qleB.resize(40, 30)
        else:
             self.qleB.setMaxLength(3)
             self.qleB.move(195, 145)
             self.qleB.resize(60, 30)

        c = int(self.x) * int(self.y)
        if len(str(c)) == 3:
            self.qleC.setMaxLength(3)
            self.qleC.move(213, 190)
            self.qleC.resize(60, 30)
        else:
            self.qleC.setMaxLength(4)
            self.qleC.move(195, 190)
            self.qleC.resize(80, 30)


    def paintEvent(self, e):
        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()
       
    def drawLines(self, qp):
        penA = QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)
        qp.setPen(penA)
        if self.isSimple(self.xa, self.ya):
            qp.drawLine(37, 103, 107, 103)
        else:
            qp.drawLine(37, 103, 107, 103)
            qp.drawLine(37, 156, 107, 156)
       
        pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
        qp.setPen(pen)
        if int(self.x/10) == int(self.y/10) or self.x % 10 == self.y % 10    \
                    or int(self.x/10) == self.x % 10 or int(self.y/10) == self.y % 10:
            qp.drawLine(170, 100, 270, 100)
        else:
            qp.drawLine(170, 100, 270, 100)
            qp.drawLine(170, 185, 270, 185)

        qp.setFont(QtGui.QFont('Decorative', 20))
        self.lblX.setFont(QtGui.QFont('Decorative', 20))
        self.lblY.setFont(QtGui.QFont('Decorative', 20))
        self.lblX.setText(str(self.x))
        self.lblY.setText(str(self.y))
        self.lblX.move(230, 40)
        self.lblX.adjustSize()
        self.lblY.move(230, 70)
        self.lblY.adjustSize()
        self.lblOp.setFont(QtGui.QFont('Decorative', 20))
        self.lblOp.move(170, 70)
        self.lblOp.adjustSize()

 

    def onChanged(self, text):

        self.lbl.setText(text)
        self.lbl.adjustSize()       
       
    def doExit(self):
        sys.exit(0)


def main():
        app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

 

실행 중인 창:

 

 

 

Posted by Scripter
,

* PyQt 내려받기: http://www.riverbankcomputing.co.uk/software/pyqt/download

 (Qt Designer 의실행 파일은 %Python27_HOME%\Lib\site-packages\PyQt4\Designer.exe 이다.)

Qt Designer 는 Visual Studio 의 Visual Basic 개발 환경과 비슷한 Python GUI 개발 도구이다.

다음은 책  Hello World! Second Edition: Computer Programming for Kids and Other Beginners 의 제 20 장에 소개되어 있는 예제를 한국어로 번안한 것이다.

 

Qt Designer 를 실행하여 다음과 같이 "새 폼" 창에서 "Main Window" 를 선택하고 "생성" 버튼을 클릭한다.

 

 

 위젯

  텍스트

 objectName

 Push Button

 Celsius to Fahrenheit >>>

 btn_CtoF

 Push Button

 <<< Fahrenheit to Celsius

 btn_FtoC

 Label

 Celsius

 

 Label

 Fahrenheit

 

 Line Edit

 

 editCel

 Spin Box

 

 spinFahr

* 주의: 폰트 설정 시 한글명 폰트(예: 바탕)를 선택하면 에러가 난다. 

 

위와 같이 디자인된 폼을 파일명 tempconv.ui 으로 저장한다.

 

소스 파일 tempconv.py 의 내용

# -*- encoding: utf-8 -*-

# PyQt 를 이용하는 온도 변환 프로그램

import sys
from PyQt4 import QtCore, QtGui, uic

form_class = uic.loadUiType("tempconv.ui")[0]                 # UI 탑재

class MyWindowClass(QtGui.QMainWindow, form_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.btn_CtoF.clicked.connect(self.btn_CtoF_clicked)  # 버튼에 이벤트 핸들러를
        self.btn_FtoC.clicked.connect(self.btn_FtoC_clicked)  #   묶는다.

    def btn_CtoF_clicked(self):                # CtoF 버튼의 이벤트 핸들러
        cel = float(self.editCel.text())         #
        fahr = cel * 9 / 5.0 + 32                 #
        self.spinFahr.setValue(int(fahr + 0.5))  #

    def btn_FtoC_clicked(self):                  # FtoC 버튼의 이벤트 핸들러
        fahr = self.spinFahr.value()             #
        cel = (fahr - 32) / 9.0 * 5
        self.editCel.setText(str(cel))           #

app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()

 

버튼에 이벤트 핸들러를 묶어 주는 구문은

                  버튼명.clicked.connect(메소드명) 

이다.

 

실행하기:

프롬프트> python convtemp.py

 

 

Posted by Scripter
,

 

명령 프롬프트> octave -qi
octave:1> x = [0, 1, 1, 0, 0];
octave:2> y = [0, 0, 1, 1, 0];
octave:3> plot(x, y), axis([-1,2, -1,2])
octave:4> axis equal
octave:5> close
octave:6> plot(x, y), axis equal, axis([-1,2, -1,2])
octave:7> close


 

 * 위의 3번 줄 명령으로 정사각형을 그렸지만, aspect ratio 가 맞지 않아 직사각형으로 보인다,

 

 

  * 그래프 창을 그대로 둔 채 위의 4번 줄 명령울 내리면, 그래프 창이 다시 열리면서 정사각형이 그려진다. (위의 3번과 4번 줄 대신 6번 줄 하나만 내려도 된다. close 는 그래프 창을 닫는 명령이다,)

 

 

Posted by Scripter
,