Home > Programming > PyQt, PIL and Windows

PyQt, PIL and Windows

March 16th, 2010

Edit: Although the following approach works on a small sample application, as the app gets more complex it’s less likely to work. I’ve moved to just using PyQt images in the GUI, and PIL images in the backend. If anyone has any ideas on how to make this work let me know in the comments.


Here’s a fun one. If you’re using PIL and PyQt4, you may want to display a PIL image in your PyQt GUI. This is a multi-step process.

kitten.jpg

kitten.jpg

  1. Create your PIL image (you can use my kitten if you want).

  2. Create an ImageQt image from your PIL image (this is PIL’s version of a QImage).

  3. Create a QPixmap from your ImageQt image.

  4. Create a QLabel and set its QPixmap to be the one just created.

And the above in code:

im = Image.open('kitten.jpg')
myQtImage = ImageQt.ImageQt(PilImage)
pixmap = QtGui.QPixmap.fromImage(myQtImage)
label = QtGui.QLabel('', self)
label.setPixmap(pixmap)

This works fine on Linux, but on Windows it crashes python.exe. I think the problem is with the ImageQt object. According to its documentation. To quote:

Creates an ImageQt object from a PIL image object. This class is a subclass of QtGui.QImage, which means that you can pass the resulting objects directly to PyQt4 API functions and methods.

On Windows it seems that it isn’t quite this easy. There is a simple solution though. Just make a new QImage from the ImageQt object:

myQtImage2 = QtGui.QImage(myQtImage1)

and this seems to turn the fake QImage into a real QImage, which can now be happily turned into a QPixmap.

Here’s a fully working program to illustrate the above in context (this is Python 2.6):

import sys
from PyQt4 import QtCore, QtGui
import Image
import ImageQt


class MyWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 400, 293)
        self.setWindowTitle('My Widget!')


        PilImage = Image.open('kitten.jpg')
        QtImage1 = ImageQt.ImageQt(PilImage)
        QtImage2 = QtGui.QImage(QtImage1)
        pixmap = QtGui.QPixmap.fromImage(QtImage2)
        label = QtGui.QLabel('', self)
        label.setPixmap(pixmap)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myWidget = MyWidget()
    myWidget.show()

    sys.exit(app.exec_())
Kitten program screenshot

Look – it works!

Categories: Programming Tags: , ,
  1. Nick
    February 5th, 2011 at 05:27 | #1

    Thank you so much! I’ve been trying to solve this issue for the past several hours and could not figure out a solution. It’s especially frustrating since the first block of code works in linux and osx, but crashes python in windows.

  2. February 5th, 2011 at 11:24 | #2

    @Nick Brilliant! Really glad I managed to help someone out :)

  3. March 20th, 2011 at 09:23 | #3

    Thanks!

    I just wanted to note that you probably don’t want to have two images. That’s why it seems quite obvious to write something like

    myQtImage = QtGui.QImage(myQtImage)
    

    But it won’t work (at least in Python 3). You should use

    myQtImage = myQtImage.copy()
    
  4. June 25th, 2013 at 00:16 | #4

    My spouse and I stumbled over here coming from a different website and thought I might check things out.

    I like what I see so now i’m following you. Look forward to looking into your web page for a second time.

    Here is my page … [If you are intending to go to European countries](http://www.footballonthetv.co.uk/blog/post/2011/10/04/Pub-landlady-beats-the-Premier-League.aspx “If you are intending to go to European countries”)

  5. June 25th, 2013 at 17:52 | #5

    Stunning quest there. What happened after?

    Good luck!

    Feel free to visit my page Lower price Brand new Orleans Resorts :: [Bernadine](http://willy-huybrechts-gallery.com/author/RosettaBo “Bernadine”) : :

  6. July 7th, 2013 at 10:58 | #6

    Just want to say your article is as astounding. The clearness for your put up is just nice and i could suppose you’re an expert in this subject. Well with your permission let me to seize your feed to stay up to date with drawing close post. Thank you one million and please carry on the gratifying work.

    My website [Hotel selling price comparison services - look for and evaluate resort prices on line for free!](http://msvtimes.com/forum/profile.php?mode=viewprofile&u=154702 “Hotel selling price comparison services – look for and evaluate resort prices on line for free!”)

  7. July 22nd, 2013 at 02:43 | #7

    I’m not sure where you’re getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for fantastic info I was looking for this info for my mission.

    Also visit my page: Twitter – [http://walkit.com/](http://walkit. com/2010/07/help-people-walk-to-your-location-using-the-new-walkit-com-widgets/ “http://walkit.com/”) -

  8. August 5th, 2013 at 20:52 | #8

    Every weekend i used to pay a quick visit this site, as i wish for enjoyment, as this this web page conations in fact good funny material too.

    Here is my homepage :: [Finding Great Hotel Deals in Europe](http://amstaff.

    fr/profile.php?mode=viewprofile&u=190469 “Finding Great Hotel Deals in Europe”)

  9. August 7th, 2013 at 07:04 | #9

    For newest news you have to pay a visit internet and on world-wide-web I found this web page as a finest web page for most up-to-date updates.

    Here is my web page; Star Motels In Phuket Phuket Island Beach Villa Phuket :: [Keesha](http://nussoccer.blogspot.de/2008/02/hostel-rooms-at-ridge-view-residences. html “Keesha”) ::

  10. September 13th, 2013 at 15:30 | #10

    An impressive share! I have just forwarded this onto a coworker who has been doing a little homework on this. And he in fact bought me dinner because I discovered it for him… lol. So allow me to reword this….

    Thank YOU for the meal!! But yeah, thanx for spending the time to talk about this issue here on your internet site.

  11. December 16th, 2013 at 19:46 | #11

    Marvelous, what a web site it is! This blog provides helpful facts to us, keep itt up.

  12. January 3rd, 2014 at 11:46 | #12

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  13. January 10th, 2014 at 21:54 | #13

    Ahaa, its nice conversation concerning this post here at this weblog, I have read all that, so now me also commenting here.

  14. January 11th, 2014 at 01:16 | #14

    With havin so much written content do you ever run into any problems of plagorism or copyright violation? My website has a lot of completely unique content I’ve either authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without my permission. Do you know any techniques to help prevent content from being stolen? I’d truly appreciate it.

  15. January 11th, 2014 at 09:32 | #15

    I was pretty pleased to uncover this web site. I want to to thank you for your time for this fantastic read!! I definitely enjoyed every part of it and I have you book marked to look at new information on your website.

  16. May 29th, 2014 at 00:16 | #16

    I’m impressed, I muset say. Seldom do I encounter a blog that’s bot educative and engaging, and let me tell you, you’ve hit the nail on the head. The issue is something that not enough men and women are speaking intelligently about. I’m very happy that I stumbled across ths during my hunt for something regarding this.

  17. July 28th, 2014 at 09:25 | #17

    I think that everything typed made a ton of sense. But, consider this, what if you composed a catchier post title? I ain’t suggesting your information is not good., but suppose you added a title that grabbed a person’s attention? I mean Skilldrick Ľ PyQt, PIL and Windows is kinda boring. You could look at Yahoo’s front page and watch how they create post headlines to grab viewers to click. You might add a video or a pic or two to grab people interested about everything’ve written. In my opinion, it could bring your blog a little bit more interesting.

  18. September 19th, 2014 at 09:16 | #18

    Soundscapes played out by means of an MP3 or CD player. Practicing yoga exercises or any other meditation techniques helps to a great extend in reducing stress and tension. Tinnitus maskers do not treat the condition except to drown out the ringing so that that a sufferer can function without being consumed by the noise.

    my homepage; hemorrhoid surgery options ([Heriberto](http://dreamtosuccess.net/effortless-hemorrhoids-systems-around-the-usa-3/ “Heriberto”))

  19. February 24th, 2015 at 12:48 | #19

    I have ben exploring for a little foor any high-quality articles or weblog posts in this sort oof house . Exploring iin Yahoo I finally stumbled upon this web site. Studying this information So i am happy too express that I have an incredibly just right uncanny feeling I discovered just what I needed. I so much undoubtedly will make certain too don?t disregard this web site andd provides it a glance on a coonstant basis.

  20. March 2nd, 2015 at 06:00 | #20

    No longer carry out tape-recording musician requirement huge budgets simply to associate with hit helping make manufacturers for warm beats.

  21. March 2nd, 2015 at 07:54 | #21

    Costs for Bitcoin purchases are actually relatively reduced ased opposed to conventional strategies of transferring money over the Net.

  22. November 5th, 2015 at 00:18 | #22

    of course like your web-site however you need to test the spelling on several of your posts. A number of them are rife with spelling problems and I find it very troublesome to tell the reality however I’ll definitely come back again.

  23. November 10th, 2015 at 06:09 | #23

    I think the article is very helpful for people,it has solved my problem,thanks!

  24. November 13th, 2015 at 19:02 | #24

    I only want one of my posts to show on my blogger homepage, but it keeps showing the latest one, and I do not want to see that post. What can I do?.

  25. November 18th, 2015 at 04:46 | #25

    They¬†are¬†free¬†to¬†enhance¬†learning¬†at¬†their¬†homes¬†too. Just¬†like¬†many¬†other¬†languages,¬†the¬†Japanese¬†language¬†is¬†also¬†very¬†rich¬†and¬†fun¬†to¬†learn,¬†whether¬†you¬†want¬†pursue¬†it¬†for¬†leisure,¬†career¬†advancement,¬†or¬†to¬†simply¬†add¬†to¬†your¬†arsenal¬†of¬†languages. ” Before children begin to speak, they listen intensely to what is being said to them and especially to things that interest them.

  26. November 27th, 2015 at 13:51 | #26

    A MACU mortgage expert can further break down the advantages and disadvantages of each [mortgage](http://www.docstoc.com/ “mortgage”) price option.

  27. December 10th, 2015 at 06:08 | #27

    I am genuinely glad to read this web site posts which consists of plenty of useful facts, thanks for providing these data.

  28. December 20th, 2015 at 03:14 | #28

    The purpose of getting placed in Google’s Organic Search results page needs deeper on-site SEO and off-site Search Engine Optimization (what’s done off the site to get rated in Google e.g. web link generation).

    my web-site; dallas fort worth seo; [Joe](http://www.gaiaonline.com/journal/?mode=view&post_id=38308185&u=37841313 “Joe”),

  29. December 23rd, 2015 at 05:12 | #29

    SEO is a collection of ideal practices that include a bunch of elements on your website as well as Net in general.

    Feel free to visit my web site … dallas video seo ([Waylon](https://disqus.com/home/discussion/channel-chaseeemhevzmqo/howtorankhigherinsearchengine_results/ “Waylon”))

  30. December 23rd, 2015 at 05:49 | #30

    Instead of SEO being of its very own distinct discipline, it will certainly be much more regularly made use of as a fundamental part that is affected by (as well as influences) the various other aspects of marketing (social media and content).

    My blog: dallas digital marketing agency ([Aaron](https://www.evernote.com/shard/s630/sh/9cf333fb-76d1-4807-8091-af2f8505b5a6/1d1b2e1aedd983207eb4f6f39bb70312 “Aaron”))

  31. January 12th, 2016 at 02:51 | #31

    You possibly can even use the proxy feature from the menus that may aid you to get invisible while adding the assets that makes this Candy Crush Soda Saga Hack the safest obtainable cheats on all around the internet.

  32. January 13th, 2016 at 14:14 | #32

    When interest rates are high, it’s possible for the cost of the loan to exceed the actual value of the vehicle being covered. They will not be at rest until and unless you have achieved your long brewing dream. It is because having your own car is most likely more beneficial to you in so many ways than not having one.

    my site – website, [Lindsay](http://gzbdirectory.com/User:LaceySaddler “Lindsay”),

  33. January 20th, 2016 at 03:25 | #33

    Thanks for ones marvelous posting! I definitely enjoyed reading it, you happen to be a great author. I will make sure to bookmark your blog and will often come back in the future.

    I want to encourage you continue your great job, have a nice evening!

  34. January 20th, 2016 at 13:52 | #34

    Let’s move onto the following line, the isolate‚ÄĚ of whey protein isolate, micro filtration is precisely what it appears like, it uses fancy ceramic filters to procedure the whey, removing fat, lactose and many additional unfavorable points without damaging the protein, incorporating harsh chemicals, or removing valuable sub fragments.

    my homepage – grass fed whey protein bars ([Yetta](http://dreamangelsinc.org/MediaCenter/Blog/tabid/119/language/es-MX/ArticleID/12/?AspxAutoDetectCookieSupport=1 “Yetta”))

  35. January 21st, 2016 at 02:36 | #35

    It’s remarkable designed for me to have a web site, which is helpful designed for my experience. thanks admin

    My blog [Anthony](http://Www.Fpdimages.com/communication-is-key/ “Anthony”)

  36. January 21st, 2016 at 02:37 | #36

    I am in fact glad to glance at this weblog posts which carries lots of useful facts, thanks for providing such information.

    My webpage: [Gladis](http://www.Irma-hesz.de/blog/index.php?itemid=52 “Gladis”)

  37. January 22nd, 2016 at 19:29 | #37

    You can dramatically change the appearance of a room by applying a fresh coat of paint.

    My web page: food products for sale – [Kristy](https://disqus.com/by/disqus_Cp83anADEI/ “Kristy”) -

  38. January 24th, 2016 at 08:11 | #38

    As any productivity nerd knows, it’s keyboard shortcuts that squeeze ‘power’ in ‘power user. it can be another good option that works using your email service.

    I get yourself a tremendous volume of email, and possess messages going back prior to the turn in the century during my archive. Mailflo is an attribute packed collaboration and project management tool for Gmail and Google apps accounts. The links that DL give are signed by google therefore, the play store sees them as actual Play Store apps. Gmail has continued to revolutionize the email industry by. [gmail login](http://almiromarket.ru/component/k2/itemlist/user/285.html “gmail login”) I get yourself a tremendous volume of email, and possess messages going back prior to the turn in the century during my archive. Mailflo is an attribute packed collaboration and project management tool for Gmail and Google apps accounts.

    The links that DL give are signed by google therefore, the play store sees them as actual Play Store apps. Gmail has continued to revolutionize the email industry by.

  39. January 28th, 2016 at 05:06 | #39

    Carry water purification tablets with you or some sort of water filter that is capable of filtering out bacteria.

    my site survival weapons to make ([Nancee](http://betotec.noip.me/djbetinho/index.php?option=com_phocaguestbook&view=phocaguestbook&id=1&Itemid=55 “Nancee”))

  40. January 29th, 2016 at 02:05 | #40

    Most people especially kids and teens prefer to play games online, whether it is strategy or puzzle or from any other category. This doesn’t mean that after you have mastered a certain plane that you will be a fully licensed pilot. But the standard single-player game’despite how unfashionable it is to play games by yourself and save games on a hard disk instead of the cloud these days’should not have been (nor needed to be) sacrificed to make it happen.

    My homepage; [simcity buildit cheat](http://socdeistvie.info/user/GenevaPritt96/ “simcity buildit cheat”)

  41. January 30th, 2016 at 18:32 | #41

    The only response I return is yes.

  42. February 11th, 2016 at 10:48 | #42

    It happens too often that marketers stop their efforts for optimizing for search terms once they reach the SERPs for those keywords. Don’t forget that you could lose that position if any of your competitor ramps up their efforts.

    Here is my web blog: Magic Submitter Review, Buy MagicSubmitter, Magic Submitter Discount ([penuelinternationalschool.com](http://penuelinternationalschool.com/component/k2/item/293-kids-time “penuelinternationalschool.com”))

  43. February 11th, 2016 at 11:22 | #43

    In North America alone, advertisers spend roughly 20 billion a yr on search engine advertising and marketing (SEM).

    my web blog: [magic submitter platform harvester](http://www.jetlag2011.com/profile.php?u=AstridExq13 “magic submitter platform harvester”)

  44. February 11th, 2016 at 18:41 | #44

    One other question is whether or not we have now now entered the age when the whole public inhabitants of social mediadom ‚ÄĒ effectively over two billion, including Facebook ‚ÄĒ turns into potential targets as social influencers or influencees.

    Here is my weblog MagicSubmitter Review, Buy Magic Submitter, MagicSubmitter Discount ([hits93.com](http://www.hits93.com/index.php/using-k2/item/70-taylor-swift-celebrates-2016-in-las-vegas-at-calvin-harris-show “hits93.com”))

  45. February 24th, 2016 at 00:38 | #45

    With nine weeks to go before the start of the National Basketball League of Canada season, the Lightning continue to work on the court and in the community prepping for what’s going to be a new-look team and in many ways, a new look league.

    my webpage: buywise ([Edith](http://maskanshomal.com/fa/component/k2/item/6-?amp “Edith”))

  46. February 25th, 2016 at 03:27 | #46

    Speecify a sealed combustion furnsce or boiler, which can deliver outside air straight into the burner and exhaust fllue gases (combustion merchandise) on to the surface, withouut the need for a draft hood or damper.

    my web site [central heating and air units lowes](http://bloodthirsty-syndicate.de/index.php?mod=users&action=view&id=98941 “central heating and air units lowes”)

Comments are closed.