Ярлыки

Показаны сообщения с ярлыком PyQt. Показать все сообщения
Показаны сообщения с ярлыком PyQt. Показать все сообщения

понедельник, 22 июля 2013 г.

PyQt: create components dinamically


What to do: create some number of cells (like matrix n by m).


1) we create ScrollArea in *.ui file, and QWidget under it:

<widget class="QScrollArea" name="scrollArea">
          <property name="mouseTracking">
           <bool>true</bool>
          </property>
          <property name="verticalScrollBarPolicy">
           <enum>Qt::ScrollBarAlwaysOn</enum>
          </property>
          <property name="horizontalScrollBarPolicy">
           <enum>Qt::ScrollBarAlwaysOn</enum>
          </property>
          <property name="widgetResizable">
           <bool>true</bool>
          </property>

          <widget class="QWidget" name="contents">
           <property name="geometry">
            <rect>
             <x>0</x>
             <y>0</y>
             <width>788</width>
             <height>223</height>
            </rect>
           </property>
          </widget>
         </widget>


2) my code:

class mainWindow(QtGui.QMainWindow, UIclass.Ui_MainWindow):
    def __init__(self, win_parent = None):
        QtGui.QMainWindow.__init__(self, win_parent)
        self.setupUi(self)
        #create QGridLayout on the first start
        self.scrollArea.widget().layout = QtGui.QGridLayout()
        self.scrollArea.widget().layout.objectName='inputLayout'
        # create cells for input data
        self.connect(self.createCells, QtCore.SIGNAL("clicked()"), self.createCellsFunc)

    # function for create cells:
    def createCellsFunc(self):
        # all was doing if we know number columns and number rows
        if str(self.text1.toPlainText()).isdigit() and str(self.text2.toPlainText()).isdigit():
            # height and length for each cell
            h=25
            l=50
            # delete all old objects (exclude layout)
            for u in self.scrollArea.widget().children():
                if u.objectName!='inputLayout':
                    # "delete some later"
                    u.deleteLater()
                    # hide now
                    u.hide()
                    # set window as parent (not ScrollArea)
                    u.setParent(self)
                
            # number of columns
            hCount=int(self.text1.toPlainText())
            # number of rows
            vCount=int(self.text2.toPlainText())

            for i in range(0,hCount):
                for j in range(0,vCount):
                    # while creating insert text '0' and determine parent
                    textArea = QtGui.QTextEdit('0', self.scrollArea)
                    # we give name to the element for fast find him
                    textArea.objectName = 'a'+str(i)+'-'+str(j)
                    # dimentions
                    textArea.setMinimumSize(l,h)
                    textArea.setMaximumSize(l,h)
                    # add created element to layer of widget (textArea - adding object, (j + 1) and (i + 1) - coordinates on layer grid of adding object)
                    self.scrollArea.widget().layout.addWidget(textArea,j+1,i+1)
            # put layer to widget
            self.scrollArea.widget().setLayout(self.scrollArea.widget().layout)
            self.scrollArea.widget().layout

3) get data from cells:

            #horizontal cells count
            hCount=int(self.text1.toPlainText())
            #vertical cells count
            vCount=int(self.text2.toPlainText())
            #check for all child objects "ScrollBox": did all data is number?
            for u in self.scrollArea.findChildren(QtGui.QTextEdit):
                try:
                    float(str(u.toPlainText()))
                except:
                    self.labelWarning.setText(QtCore.QString(u'Some data is not number'))
                    return None
            
            #put data to array
            a,a0=list(),list()
            for j in range(0,vCount):
                for i in range(0,hCount):
                    for u in self.scrollArea.findChildren(QtGui.QTextEdit):
                        if u.objectName=='a'+str(i)+'-'+str(j):
                            a0.append(float(u.toPlainText()))
                a.append(a0)
                a0=list()

понедельник, 18 марта 2013 г.

PyQt: show SVG

#scale increase 
self.connect(self.incScaleButton, QtCore.SIGNAL("clicked()"),lambda who="incScale": self.incScale())
 #scale decrease 
 self.connect(self.decScaleButton, QtCore.SIGNAL("clicked()"),lambda who="decScale": self.decScale())
 #create Scene for show diagrams
 self.sc=QtGui.QGraphicsScene(self.graphicsView)

 def incScale(self):
     self.scale+=0.1
     self.printGDP(scale=self.scale)

 def decScale(self):
     self.scale-=0.1
     self.printGDP(scale=self.scale)

 #show diagram: 
 filename=fileArrayt[fileNumber]
 #create object for SVG modification 
 r=QtSvg.QSvgRenderer()
 #load data 
 r.load(QtCore.QByteArray(arrayToSave))
 #change rectangle for our image 
 r.setViewBox(QtCore.QRectF(0.0, 0.0, 3200.0, 2000))
 #create additional element
 item=QtSvg.QGraphicsSvgItem()
 #put our image into it 
 item.setSharedRenderer(r)
 #change scale
 item.setScale(1.0)
 #clear Scene, change size of it 
 self.sc.clear()
 self.sc.setSceneRect(QtCore.QRectF(0.0, 0.0, 3200.0, 2000))
 #change position of item into Scene 
 item.setPos(QtCore.QPointF(10,50))
 #add item to Scene 
 self.sc.addItem(item)
 #for QGraphicsView set Scene, define "view point" 
 self.graphicsView.setScene(self.sc)
 self.graphicsView.centerOn(0,0)

суббота, 3 ноября 2012 г.

PyQt: file save dialog (in windows)


make class:

class OpenFile(QtGui.QMainWindow):
   def __init__(self, parent=None):
       QtGui.QMainWindow.__init__(self, parent)
       self.setGeometry(300, 300, 350, 300)
       self.setWindowTitle('SaveFile')
       self.textEdit = QtGui.QTextEdit()
       self.setCentralWidget(self.textEdit)
       self.statusBar()
       self.setFocus()
       exit = QtGui.QAction(QtGui.QIcon('open.png'), 'Open', self)
       exit.setShortcut('Ctrl+O')
       exit.setStatusTip('Open new File')
       self.connect(exit, QtCore.SIGNAL('triggered()'), self.showDialog)
       menubar = self.menuBar()
       file = menubar.addMenu('&File')
       file.addAction(exit)

   def showDialog(self,text):
       filename = QtGui.QFileDialog.getSaveFileName(self, 'Save file', '')
       f=open(filename.toUtf8().data().decode('utf-8').encode('cp1251'),'w')
       f.write(text.toUtf8().data().decode('utf-8').encode('cp1251'))
     
in MainWindow class writing:
    def __init__(self, win_parent = None):
        ...
        #save stats in file
        self.connect(self.saveButton, QtCore.SIGNAL("clicked()"), self.saveFile)

    def saveFile(self):
        cd = OpenFile()
        cd.showDialog(self.textStatistic.toPlainText())

PyQt: pause in child thread


while (main_window.paused):
    time.sleep(1)

main_window.paused changing by current button.

PyQt: change table data => refresh headers


        #change table data => refresh headers
        self.connect(self.Station, QtCore.SIGNAL("cellPressed(int,int)"), self.updateHeader)
        self.connect(self.Train, QtCore.SIGNAL("cellPressed(int,int)"), self.updateHeader)

Python: use Psyco in PyQt4 thread


import psyco

#make function bind in thread before call it
psyco.bind(myFunc())
myFunc()

transfer data between threads in PyQt


I create signal in start function (in the other words - "wait for signal"):

self.connect(self.s1,QtCore.SIGNAL('printStat(PyQt_PyObject)'),self.printStat)

s1 - child thread;
printStat(PyQt_PyObject) - signal name, which send from thread s1 to main thread;
self.printStat  - function for our reaction by signal ( self = QMainWindow() ).


I create sending signal in child thread:

self.emit(QtCore.SIGNAL('printStat(PyQt_PyObject)'),[list of transfer vars])

I can transfer any PyQt- or/and Python-objects.

Function printStat must get transfer objects:

    def printStat(self, [list of transfer vars]):

show SVG via QGraphicsView

in class QMainWindow we create QGraphicsScene on object myGraphicsView:

self.sc=QtGui.QGraphicsScene(self.myGraphicsView)

In function for show SVG, we write:

r=QtSvg.QSvgRenderer()
r.load(QtCore.QByteArray(mySVG))
r.setViewBox(QtCore.QRectF(0.0, 0.0, 3500.0, 3500.0))
item=QtSvg.QGraphicsSvgItem()
item.setSharedRenderer(r)
item.setScale(20.0)
self.sc.clear()
self.sc.setSceneRect(QtCore.QRectF(0.0, 0.0, 2000.0, 1000.0))
item.setPos(QtCore.QPointF(10,50))
self.sc.addItem(item)
self.graphicsView.setScene(self.sc)
self.graphicsView.centerOn(0,0)

mySVG - source of the SVG-file (as text)

Picture size is 3500 by 3500 pixels.

Threads in PyQt4


I want to create threads in PyQt4 (for normal use GUI).

Make thread class:

class solveThread(QtCore.QThread):
        def run(self):

              <what do you want doing>

Check for use thread with same name and kill it if yes:

        if (hasattr(self,'s1')):
            del(self.s1)
        self.s1=solveThread()



If I want terminate thread by button, I use variable self.isExit=0 in infinite while loop (I don't use Thread.terminate() ). And I use refresh GUI each 5-10 sec (otherwise my GIU is freezing).

Python: coding in console, which make in cx_Freeze


I make console application in cx_Freeze. And I have follow error with unicode:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27
, in <module>
    exec code in m.__dict__
  File "carsDistrib.py", line 117, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-12: ordi
nal not in range(128)

# fix by set default coding:
try:
    sys.setdefaultencoding("
cp1251")
except AttributeError:
    pass

Qt: use Layout for tab in Designer


by follow steps:
- create tab
- create Layout on this tab
- delete Layout from tree of objects
- property Layout must save for this tab

On the video:
http://www.youtube.com/watch?v=8JYEdXDhrTY

PyQt4: python's class from ui-file


I create python's class always after changed of my GUI:
pyuic4 MainWindow.ui -o UIclass.py

where MainWindow.ui - file of QtDesigner, UIclass.py - python's class.

PyQt4: connect


Task: run function mySlotFunction on changing value in combobox:

There is bad idea:
self.connect(self.myComboBox, QtCore.SIGNAL("currentIndexChanged(-1)"), self.
mySlotFunction)  

There is good idea:
self.connect(self.myComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.mySlotFunction)   

PyQt: change table headers


We can use table headers with follow:

horizontalHeaderItem ( int column ) const
verticalHeaderItem ( int column ) const

PyQt: how to track change selected cell


#if changed selected cell we print number of current row:
self.connect(self.myTableWidget, QtCore.SIGNAL("itemSelectionChanged()"), self.printCurrRow)

Python to EXE: cx_Freeze is work!

1) on windows installing cx_Freeze.

2) D:\MyProject>C:\Python27\Scripts\cxfreeze myProject_main.py --target-dir folderForExe

myProject_main.py - main file of the project (it's usually run by Python)
folderForExe - target folder for EXE and all libraries.

problem with encoding in PyQt4


Python2.7, Eric4, PyQt4 
I have follow problem:
when I send list to form for fill ComboBox: in ComboBox I see abracadabra. My coding is utf-8.

My code:
sectList=[i[0] for i in sectionsDict.items()]
print(sectList)
main_window.selectSection.addItems(sectList)

Function "print" insert for see what doing here.

Solve of the problem:
sectList=[unicode(i[0], 'cp1251') for i in sectionsDict.items()]
print(sectList)
main_window.selectSection.addItems(sectList)