analitics

Pages

Saturday, July 8, 2017

Python Qt4 - part 006.

Today I will deal with QFileDialog widget.
You can read the more about this widget here.
This allows us to open a dialog to load a resource - a file.
The example comes with the base PyQt4 application window with a my_example dialog from fileDialogSample python class.
Into this python class, I have some variable for the file: file_name, data and my_file_open.
The my_text_edit for text area and my_button to open the QFileDialog.
Also, the vbox variable to put all on QVBoxLayout from the application.
Let's see the example:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class fileDialogSample(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        #make text area and button
        self.my_text_edit = QtGui.QTextEdit()
        self.my_button = QtGui.QPushButton('Select File', self)

        #open the showDialog
        self.my_button.clicked.connect(self.showDialog)

        #put all into application area
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.my_text_edit)
        vbox.addWidget(self.my_button)
        self.setLayout(vbox)

        #set title and geometry of application
        self.setWindowTitle('File Dialog example')
        self.setGeometry(50, 50, 300, 300)

    #make a function with seeting for my QFileDialog
    def showDialog(self):
        file_name = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 'C://')
        my_file_open = open(file_name)
        data = my_file_open.read()
        self.my_text_edit.setText(data)
        my_file_open.close()

#run the application 
app = QtGui.QApplication(sys.argv)
my_dialog = fileDialogSample()
my_dialog.show()
sys.exit(app.exec_())
Now, just press the Select File button, take a text file and open it.

Friday, July 7, 2017

Python Qt4 - part 005.

Another example with PyQt4 that allow seeing images over the internet.
Here's another simple example with PyQt4 that allows you to view images on the internet.
You can use any image on the internet to display with this python script.
This example is done in two steps:
  • take a single image from the internet - httplib python module;
  • displaying - PyQt4 python module
from PyQt4 import QtGui
import sys
import httplib

def getTempPNG():
   conn = httplib.HTTPConnection("www.meteoromania.ro")
   conn.request("GET", "/sateliti/img/id814/id814_2017070718.png")
   return conn.getresponse().read()

def main():
   app = QtGui.QApplication(sys.argv)
   png = getTempPNG()
   pixmap = QtGui.QPixmap()
   pixmap.loadFromData(png)
   label = QtGui.QLabel()
   label.setPixmap(pixmap)
   label.setWindowTitle('METEOSAT-10 Thermal Infrared Channel 10.8 micrometers Glowing temperature')
   label.show()
   app.exec_()

if __name__ == '__main__':
   main()
The result can be seen in this screenshot: