Re: [PyQt] A good PyQt “Primer”?
On Fri, 11 Jan 2013 17:26:29 +0530 šãñ wrote: > are you planning to come with next version of this book, and if u r > consider PySide differences and some apps example based on Pyside too.. I would very much like to do a new edition with examples that work with both PyQt and PySide. However, I have other book commitments at the moment, so do not know when (or even if) I will be able to do a new edition. It is possible to port most of the book's examples to PySide already. See: http://www.qtrac.eu/pyqtbook.html#pyside [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Go" - ISBN 0321774639 http://www.qtrac.eu/gobook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] A good PyQt “Primer”?
On Thu, 10 Jan 2013 23:50:05 +0530 šãñ wrote: > Guess what the book doesnt talks about QFileSystemModel anywhere at > all :( That's because QFileSystemModel was introduced in Qt 4.4, after the book was published. The book does cover Qt's model/view architecture, including QAbstractItemModel which is QFileSystemModel's base class. > On Wed, Dec 12, 2012 at 12:43 AM, šãñ wrote: > > > I have started with this very basic stuff to begin with... > > > > > > > > On Wed, Dec 12, 2012 at 12:41 AM, Nico Dufort > > wrote: > > > >> This one is fairly easy to follow: > >> > >> http://zetcode.com/tutorials/pyqt4/ > >> > >> also for PySide: > >> http://zetcode.com/gui/pysidetutorial/ > >> > >> > >> > >> On Tue, Dec 11, 2012 at 3:08 AM, šãñ wrote: > >> > >>> I want this book but I don't have cash to buy it. > >>> > >>> > >>> On Tue, Dec 11, 2012 at 4:30 PM, Tony Lynch wrote: > >>> > >>>> We have this book and have found it to be an excellent guide, > >>>> > >>>> Tony > >>>> > >>>> > -Original Message- > >>>> > From: pyqt-boun...@riverbankcomputing.com [mailto:pyqt- > >>>> > boun...@riverbankcomputing.com] On Behalf Of Mark Summerfield > >>>> > Sent: 11 December 2012 09:36 > >>>> > To: pyqt@riverbankcomputing.com > >>>> > Subject: Re: [PyQt] A good PyQt “Primer”? > >>>> > > >>>> > On Tue, 11 Dec 2012 09:19:50 + > >>>> > Pietro Moras wrote: > >>>> > > > >>>> > > Desiring to test my hands on PyQt (and Python 3) I'd love to be > >>>> > > advised which the PyQt “primer” to start from (by the way: > >>>> > > having found the ordinary PyQt documentation utterly > >>>> > > unpractical for > >>>> > beginners). Thank > >>>> > > you.- P.M. > >>>> > > >>>> > Although my "Rapid GUI Programming with Python and Qt" is Python > >>>> > 2- based, the differences with Python 3 aren't great and I > >>>> > provide Python 3 versions of the examples. > >>>> > > >>>> > -- > >>>> > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > >>>> > C++, Python, Qt, PyQt - training and consultancy > >>>> > "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 > >>>> > http://www.qtrac.eu/pyqtbook.html > >>>> > ___ > >>>> > PyQt mailing listPyQt@riverbankcomputing.com > >>>> > http://www.riverbankcomputing.com/mailman/listinfo/pyqt > >>>> ___ > >>>> PyQt mailing listPyQt@riverbankcomputing.com > >>>> http://www.riverbankcomputing.com/mailman/listinfo/pyqt > >>>> > >>> > >>> > >>> > >>> -- > >>> ** > >>> > >>> [image: San's personal blog] > >>> <http://feeds.feedburner.com/SanLuthraBlog> > >>> > >>> * > >>> * > >>> > >>> > >>> ___ > >>> PyQt mailing listPyQt@riverbankcomputing.com > >>> http://www.riverbankcomputing.com/mailman/listinfo/pyqt > >>> > >> > >> > >> > >> -- > >> "Attention, attention. Here and now, boys," the mynah repeated. "Here > >> and now, boys." > >> > > > > > > > > -- > > ** > > > > [image: San's personal blog] > > <http://feeds.feedburner.com/SanLuthraBlog> > > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] A good PyQt “Primer”?
On Tue, 11 Dec 2012 11:28:52 + Joe Borġ wrote: > The book is free. No it isn't! Although people have done rip-offs of the PDF from time to time, the book is commercial and must be paid for. If you see free copies please let me know so that I can inform the publisher's legal department. > > > > Regards, > Joseph David Borġ > http://www.jdborg.com > > > > On 11 December 2012 11:08, šãñ wrote: > > > I want this book but I don't have cash to buy it. > > > > > > On Tue, Dec 11, 2012 at 4:30 PM, Tony Lynch wrote: > > > >> We have this book and have found it to be an excellent guide, > >> > >> Tony > >> > >> > -Original Message- > >> > From: pyqt-boun...@riverbankcomputing.com [mailto:pyqt- > >> > boun...@riverbankcomputing.com] On Behalf Of Mark Summerfield > >> > Sent: 11 December 2012 09:36 > >> > To: pyqt@riverbankcomputing.com > >> > Subject: Re: [PyQt] A good PyQt “Primer”? > >> > > >> > On Tue, 11 Dec 2012 09:19:50 + > >> > Pietro Moras wrote: > >> > > > >> > > Desiring to test my hands on PyQt (and Python 3) I'd love to be > >> > > advised which the PyQt “primer” to start from (by the way: having > >> > > found the ordinary PyQt documentation utterly unpractical for > >> > beginners). Thank > >> > > you.- P.M. > >> > > >> > Although my "Rapid GUI Programming with Python and Qt" is Python 2- > >> > based, the differences with Python 3 aren't great and I provide > >> > Python 3 versions of the examples. > >> > > >> > -- > >> > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > >> > C++, Python, Qt, PyQt - training and consultancy > >> > "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 > >> > http://www.qtrac.eu/pyqtbook.html > >> > ___ > >> > PyQt mailing listPyQt@riverbankcomputing.com > >> > http://www.riverbankcomputing.com/mailman/listinfo/pyqt > >> ___ > >> PyQt mailing listPyQt@riverbankcomputing.com > >> http://www.riverbankcomputing.com/mailman/listinfo/pyqt > >> > > > > > > > > -- > > ** > > > > [image: San's personal blog] > > <http://feeds.feedburner.com/SanLuthraBlog> > > > > * > > * > > > > > > ___ > > PyQt mailing listPyQt@riverbankcomputing.com > > http://www.riverbankcomputing.com/mailman/listinfo/pyqt > > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Go" - ISBN 0321774639 http://www.qtrac.eu/gobook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] A good PyQt “Primer”?
On Tue, 11 Dec 2012 09:19:50 + Pietro Moras wrote: > > Desiring to test my hands on PyQt (and Python 3) I'd love to be advised > which the PyQt “primer” to start from (by the way: having found the > ordinary PyQt documentation utterly unpractical for beginners). Thank > you.- P.M. Although my "Rapid GUI Programming with Python and Qt" is Python 2-based, the differences with Python 3 aren't great and I provide Python 3 versions of the examples. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] problem running pyqt on xubuntu
Hi Baz, On Sun, 21 Oct 2012 00:44:58 +0100 Baz Walter wrote: > On 20/10/12 08:11, Mark Summerfield wrote: > > Hi, > > > > I have built local versions of Qt 4.8.3, Python, SIP, and PyQt on an > > Xubuntu machine which has Qt 4.8.1 as its system Qt: > > > > $ cd qt483src > > $ ./configure -prefix ~/opt/qt483 > > $ make && make install > > > > $ cd py33src > > $ ./configure --prefix ~/opt/py33 > > $ make && make install > > > > $ cd sip414src > > $ ~/opt/py33/bin/python3 configure.py > > $ make && make install > > > > $ cd pyqt495src > > $ ~/opt/py33/bin/python3 configure.py -q ~/opt/qt483/bin/qmake > > $ make && make install > > > > $ ./opt/py33/bin/python3 mypyqtapp.pyw > > Cannot mix incompatible Qt library (version 0x40801) with this library > > (version 0x40803) Aborted (core dumped) > > > > So clearly, despite trying to build using my local Qt, PyQt seems to be > > looking at the system Qt. > > > > Is there a solution for this? > > One of the simplest solutions is to use LD_LIBRARY_PATH. > > Create a wrapper "pyqt483" script like this: > > #!/bin/sh > > export LD_LIBRARY_PATH="path/to/qt4/lib" > > exec "path/to/bin/python" "$@" > > Then you can test your pyqt apps like this: > > $ pyqt483 mypyqtapp.pyw I will try that next week. But I still don't understand why, if I use -q when I build PyQt, it makes any reference to another Qt at all. So, ISTM, that this is a PyQt bug... -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] problem running pyqt on xubuntu
On Sat, 20 Oct 2012 03:21:51 -0400 Scott Kitterman wrote: > On Saturday, October 20, 2012 08:11:29 AM Mark Summerfield wrote: > > I have built local versions of Qt 4.8.3, Python, SIP, and PyQt on an > > Xubuntu machine which has Qt 4.8.1 as its system Qt: > > ... > > > So clearly, despite trying to build using my local Qt, PyQt seems to be > > looking at the system Qt. > > > > Is there a solution for this? > > Upgrading to the newest Xubuntu release where 4.8.3 is the system Qt > would be one way to do it. Yes, and so would doing a local install of 4.8.1. But my whole purpose is to be able to have many local builds of different combinations of Py x Qt x PyQt for testing purposes. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] problem running pyqt on xubuntu
Hi, I have built local versions of Qt 4.8.3, Python, SIP, and PyQt on an Xubuntu machine which has Qt 4.8.1 as its system Qt: $ cd qt483src $ ./configure -prefix ~/opt/qt483 $ make && make install $ cd py33src $ ./configure --prefix ~/opt/py33 $ make && make install $ cd sip414src $ ~/opt/py33/bin/python3 configure.py $ make && make install $ cd pyqt495src $ ~/opt/py33/bin/python3 configure.py -q ~/opt/qt483/bin/qmake $ make && make install $ ./opt/py33/bin/python3 mypyqtapp.pyw Cannot mix incompatible Qt library (version 0x40801) with this library (version 0x40803) Aborted (core dumped) So clearly, despite trying to build using my local Qt, PyQt seems to be looking at the system Qt. Is there a solution for this? Thanks! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] Menu icons missing in Xfce
Hi, I have a Python 3/PyQt 4 application that has standard menus and toolbars and works fine under GNOME 2 on Debian 6. However, on Xubuntu (Xfce 4.8) the icons only show up in the toolbars not in the menus. Yet other applications (e.g., firefox, Archive Manager) have icons in their menus. Does anyone know the fix for this? Thanks! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] vertical alignment of richtext in a table view
Hi Wolfgang, On Sat, 18 Dec 2010 18:56:36 +0100 Wolfgang Rohdewald wrote: > On Dienstag 07 September 2010, Mark Summerfield wrote: > > > > The offset you need might be made up of the > > > > option.decorationSize's width; not sure about the height > > > > offset. > > > > > > > > > > > > decorationSize is (16,16) - that does not explain it. > > > > Then I'm not sure. Could try experimenting with the label's > > indent, margin, and frameWidth. > > now I found the problem. > > This misplaces the text: > > class RichTextColumnDelegate(QStyledItemDelegate): > label = QLabel() > def paint(self, painter, option, index): > ... > self.label.render(painter, option.rect.topLeft()) > > I have to do: > painter.save() > painter.translate(option.rect.topLeft()) > self.label.render(painter) > painter.restore() Yes, I just checked with the PyQt book's examples and that's almost the same as what I do: def paint(self, painter, option, index): ... painter.save() ... painter.translate(option.rect.x(), option.rect.y()) ... painter.restore() -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] How to destroy SIGNAL
On Mon, 15 Nov 2010 21:20:35 + starglider develop wrote: > Hi, > I have a QWidgetGrid that need to response to a double click signal, > but sometimes it as the > double grid signal disconnected to allow the user to directly edit the > cells, and a itemChanged signal was > implemented, my problem is that I can't delete/destroy de signals > according to my needs. > > Any help will be great. > > Thank you in advance. Have you tried using QObject.blockSignals()? This doesn't create or destroy them but stops/starts them being acted upon. http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#blockSignals And if you really want to delete a signal use QObject.disconnect(): http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#disconnect -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] vertical alignment of richtext in a table view
On Tue, 7 Sep 2010 12:56:59 +0200 Wolfgang Rohdewald wrote: > On Dienstag 07 September 2010, Mark Summerfield wrote: > > I should have mentioned before that it is better to inherit > > from QStyledItemDelegate rather than QItemDelegate. I'd try > > that first & see if that improves things at all. > > makes no difference. Maybe not, but still better practice. > > The offset you need might be made up of the > > option.decorationSize's width; not sure about the height > > offset. > > decorationSize is (16,16) - that does not explain it. Then I'm not sure. Could try experimenting with the label's indent, margin, and frameWidth. > > Using QTextDocument is fine for computing the size hint, > > although for efficiency you might create a class-level > > QTextDocument and reuse it. > > done. Good. > > > (There are other possibilities > > too, that I cover in Advanced Qt Programming, but can't > > recall off hand.) > > just ordered. I hope it is as excellent as your book about > rapid GUI programming with Python and Qt. I hope so too:-D > my latest version of this delegate is here: > http://websvn.kde.org/trunk/KDE/kdegames/kajongg/src/genericdelegates.py?view=markup I just looked at that and noticed that you're implementing a GenericDelegate. That works fine, but Qt now allows you to set row- and column-specific delegates so having a GenericDelegate is no longer needed. Instead, just create the delegates that you need, e.g., RichTextDelegate, and set that on the row(s) and column(s) its needed for. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] vertical alignment of richtext in a table view
On Tue, 7 Sep 2010 01:37:45 +0200 Wolfgang Rohdewald wrote: > On Montag 06 September 2010, Mark Summerfield wrote: > > I'm tending to use a differnt approach for rich text delegates > > nowadays. Instead of using a QTextDocument, I store a > > class-level QLabel, something like this: > > your solution certainly looks cleaner than my temporary fix > (document.setDocumentMargin(7.0)), and it solves > the problem of painting outside of the field. > > but it does not quite work for me. Your untested example > leaves the fields blank, it seems I have to give the > renderer a position. Using view.pos() + option.rect.topLeft(), > labels are still too far up and left. > The magical offset (3,25) puts them all in the right place. > How can I compute the correct place instead? I should have mentioned before that it is better to inherit from QStyledItemDelegate rather than QItemDelegate. I'd try that first & see if that improves things at all. The offset you need _might_ be made up of the option.decorationSize's width; not sure about the height offset. Using QTextDocument is fine for computing the size hint, although for efficiency you might create a class-level QTextDocument and reuse it. (There are other possibilities too, that I cover in Advanced Qt Programming, but can't recall off hand.) > > class RichTextColumnDelegate(QtGui.QItemDelegate): > > label = QtGui.QLabel() > > def __init__(self, parent=None): > super(RichTextColumnDelegate, self).__init__(parent) > > def paint(self, painter, option, index): > text = index.model().data(index, > QtCore.Qt.DisplayRole).toString() > self.label.setText(text) > self.label.setFixedSize(option.rect.size()) > view = self.parent().parent().view > topLeft = view.pos() + option.rect.topLeft() + > QtCore.QPoint(3, 25) > self.label.render(painter, topLeft) > > def sizeHint(self,option,index): > # still uses QTextDocument as in your book > > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] vertical alignment of richtext in a table view
Hi Wolfgang, On Sun, 5 Sep 2010 10:55:04 +0200 Wolfgang Rohdewald wrote: > Hi, > > in Mark Summerfields book "Rapid GUI programming with Python > and QT", there is an example on page 485 with a table column > having a delegate that displays richtext. In the book, > the text in this column has a vertical alignment in the middle > of the cells, just like the other columns. > > but if I execute that example (from the downloadable source: > chap16/carhirelog.pyw), the rich text is vertically not > in the middle but above. How can I make it align vertically > just like a normal column? > > His book has another such table chap14, page 436 / > ships_delegate.pyw. > Here, both the image in the book and the executable show > the same wrong vertical alignment. > > BTW interesting things happen if the column with richtext > is resized to a minimum: the delegate draws outside of its > available horizontal space, showing text to the right of > the rightmost column. I'm tending to use a differnt approach for rich text delegates nowadays. Instead of using a QTextDocument, I store a class-level QLabel, something like this: # UNTESTED! def paint(self, painter, option, index): text = index.model().data(index, Qt.DisplayRole).toString() self.label.setText(text) # self.label is a QLabel with alignment # etc. set up as one likes in the # delegate's constructor # might want to change the label's palette here, depending on # the selection state self.label.setFixedSize(option.rect) self.label.render(painter) Hope this helps:-) > (using pyqt 4.7.3 with qt4-4.7.0-rc1) > > this is the paint of the delegate: > > def paint(self, painter, option, index): > text = index.model().data(index, Qt.DisplayRole).toString() > palette = QApplication.palette() > document = QTextDocument() > document.setDefaultFont(option.font) > if option.state & QStyle.State_Selected: > document.setHtml(QString("%2") \ > .arg(palette.highlightedText().color().name()) \ > .arg(text)) > else: > document.setHtml(text) > painter.save() > color = palette.highlight().color() \ > if option.state & QStyle.State_Selected \ > else QColor(index.model().data(index, > Qt.BackgroundColorRole)) > painter.fillRect(option.rect, color) > painter.translate(option.rect.x(), option.rect.y()) > document.drawContents(painter) > painter.restore() > > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] setCursor does not seem to work as expected in graphicsScene/View
On Wed, 25 Aug 2010 10:54:49 +0200 "Christopher M. Nahler" wrote: > I'll take it as an "if all else fails" solution :-) not giving hope > up now! Good for you:-) > I have changed the item cursors and view cursors to be differnt to > see which one wins as sometimes it looked as if it was working. But > it turns out its the item cursors that wins. I would expect items to win over the view since they are logically on top of the view. > After reading more on cursors I have found that application override > cursor works with a stack. Is this also the case with the "normal" > item cursors? Do I need to unset cursors? I see a reference to a > unsetCursor() function but cannot find details to it. The application cursor does use a stack. For QWidgets & QGraphicsItems a call to unsetCursor() means "I don't have a cursor preference so use my parent's cursor over me". > > Chris > > On 25.08.2010 10:30, Mark Summerfield wrote: > > On Wed, 25 Aug 2010 10:16:08 +0200 > > "Christopher M. Nahler" wrote: > > > >> I have done more tests and found the following: > >> > >> - I have tried self.update() in various locations of updateItems() > >> and it did not change the behaviour. > >> > >> - The changing of cursors always work with the item though. > >> > >> - I have also tried commenting the item.update() line and this does > >> not change the behaviour so I think update() is not relevant to > >> cursor changes. > >> > >> - I tried it with commenting the loop at the end where i change the > >> item cursors and that changed the behaviour. So somehow changing > >> the cursor of an item has an effect on the view. > >> > >> Any ideas or tips? Is this a bug or am I doing something the wrong > >> way? If I cannot get the cursors to work right I need to change my > >> approach on how i tell the user which mode he is working in. > >> > > One simple "cheat" is to create a QGraphicsItem that is the same > > size as the scene and give it a big negative zValue so that it is > > always at the back and to change the icon on that item... Haven't > > tried this though. > > > > [snip] > > > > > > > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] setCursor does not seem to work as expected in graphicsScene/View
On Wed, 25 Aug 2010 10:16:08 +0200 "Christopher M. Nahler" wrote: > I have done more tests and found the following: > > - I have tried self.update() in various locations of updateItems() > and it did not change the behaviour. > > - The changing of cursors always work with the item though. > > - I have also tried commenting the item.update() line and this does > not change the behaviour so I think update() is not relevant to > cursor changes. > > - I tried it with commenting the loop at the end where i change the > item cursors and that changed the behaviour. So somehow changing the > cursor of an item has an effect on the view. > > Any ideas or tips? Is this a bug or am I doing something the wrong > way? If I cannot get the cursors to work right I need to change my > approach on how i tell the user which mode he is working in. One simple "cheat" is to create a QGraphicsItem that is the same size as the scene and give it a big negative zValue so that it is always at the back and to change the icon on that item... Haven't tried this though. [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] setCursor does not seem to work as expected in graphicsScene/View
Hi Christopher, I think one factor is that you call update() on the items after changing the cursor, but not on the view. I tried this: def updateItems(self): print("view updateItems") m = self.scene().viewMode() if m == MyScene.SELECTMODE: print("is select mode") itemCursor = Qt.OpenHandCursor elif m == MyScene.EDITMODE: print("is edit mode") itemCursor = Qt.ForbiddenCursor elif m == MyScene.DRAWMODE: print("is draw mode") itemCursor = Qt.CrossCursor items = self.scene().items() for item in items: item.setCursor(itemCursor) item.update() self.setCursor(itemCursor) self.update() which had an interesting effect, i.e., the view's cursor does change, but it doesn't work as I expected, and I don't have time to look into it further:-( [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Trouble implementing a TableView model
Hi Bernard, On Tue, 3 Aug 2010 08:09:25 -0400 "Bernard Van Der Stichele" wrote: > A while back, I had asked the group how I could implement a numeical > sort on a TableWidget. > Someone kindly showed me how to implement a model, associated with a > TableView. The sample code was posted here: > http://diotavelli.net/PyQtWiki/Sorting%20numbers%20in%20columns > > I'm having problems implementing this in my app. In this simple > example, I use Qt Designer to create a MainForm containing a > TableView (gridView), a LineEdit (queryBox) and a PushButton > (runQueryBtn). The designer files (.ui and ui_xxx.py) generated > defines the TableView in a couple of lines - I have not used the > Designer to change any of the default object properties. > > The problem I have is that the TableView remains blank. I do not > understand what I'm missing, as I tried to follow the same workflow > as provided by the code linked-to above.. > The code works, in that the data I want to display is retrieved from > a database and I receive no runtime warnings or errors. > > Any help is greatly appreciated... this is probably one of those > simple newbie errors. > > My application shell is as follows: [snip] I've only had the chance for a quick glimpse at your code. One thought would be to replace model with self.model because I think it might be getting garbage collected. (Or give the model a parent.) BTW You might be able to avoid a proxy altogether since you're using standard items: look up QStandardItemModel.sortRole() & QStandardItemModel.setSortRole(). [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] Book: Advanced Qt Programming [C++/Qt]
Hi, I am delighted to announce that a new book, "Advanced Qt Programming" (ISBN 0321635906), is now available in the U.S., and soon elsewhere. The book is aimed at C++/Qt programmers and covers ideas and techniques that are too advanced or specialized (but not necessarily difficult) for a first book on Qt. I believe that this book will be helpful and useful to PyQt4 programmers who have a basic familiarity with C++ since most of the Qt techniques shown apply equally to C++ and PyQt4. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Rapid GUI Programming with Python and Qt
Hi Christophe, On Tue, 20 Jul 2010 09:53:21 +0200 (CEST) wrote: > Hello, > >>> I would very much like to do a new edition of the PyQt book, > >>> but it will probably not be for another year or two due > >>> to other commitments. > > I'll be patient... :-( I hope that the new edition will show new > feature like playing with WebKit and JavaScript. I certainly hope to cover WebKit. > >>> I want the next edition to be based on Python 3.1 (or later). > > Great. > > > >>> Also, I am hoping that by the time I'm ready to start on it PySide > >>> will support Python 3 and will be sufficiently compatible with > >>> PyQt that I can cover both in the same book without confusing > >>> readers. > > That's interesting because PySide proposes a package for Mac. But > there is no Windows installer for the moment... > > I'm dreaming if a Mac package for PyQt... You mean a binary package I guess... that's one for Phil:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Rapid GUI Programming with Python and Qt
Hi Sathishkumar, On Tue, 20 Jul 2010 10:33:34 +0530 Sathishkumar Duraisamy wrote: > Hi Mark Summerfield, > > I am fan of your book "Rapid GUI Programming with Python and Qt". Its > pleasure to have new edition. But two year is little long I know! But it takes a long time to write a book or to do a new edition, and for this year and next I already have another book pencilled in! > I have found the pyqt does not have any support for the classes for > embedded linux. But David Boddie has given some support for it in > http://bitbucket.org/dboddie/pyqt4-for-embedded-linux. I wish please > you to include support for it in next edition, such as how to port it > to embedded linux / embedded systems AFAIK PyQt doesn't target embedded systems, at least not right now. But PySide specifically does target embedded systems, e.g. Maemo 5, and my guess is that they'll also support MeeGo. I'll look into this area when I start planning the next edition and will cover it if possible. > > Sathishkumar > > On Mon, Jul 19, 2010 at 9:07 PM, Mark Summerfield > wrote: > > > On Mon, 19 Jul 2010 15:06:12 +0200 (CEST) > > wrote: > > > > > Hello, > > > I would ike to have infos about the future new version for Python > > > 3 of this great book. Is there a publication date ? > > > > Hi "C", > > > > I would very much like to do a new edition of the PyQt book, but it > > will probably not be for another year or two due to other > > commitments. > > > > I want the next edition to be based on Python 3.1 (or later). Also, > > I am hoping that by the time I'm ready to start on it PySide will > > support Python 3 and will be sufficiently compatible with PyQt that > > I can cover both in the same book without confusing readers. > > > > For those who can't wait I have converted all the book's examples to > > Python 3.0 (using PyQt API 1) and to Python 3.1 (using PyQt API 2). > > > > I had expected the conversion to Python 3.1 and API 2 to be rather > > difficult, but in the end it was pretty straightforward, so the > > differences between what's shown in the book and the Python 3.1 > > versions of the examples are either non-existent or easy to see and > > understand. > > > > I've put a few notes on the most problematic classes at the bottom > > of the book's web page: > > http://www.qtrac.eu/pyqtbook.html > > (This is also where the links to the Python 3 examples are located.) > > > > On a personal note, last week I finished converting all my own > > Python programs to Python 3.1 using the 2to3 tool and then manually > > converting str % usage to str.format(). This includes some PyQt GUI > > programs that I use every day:-) > > > > -- > > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > >C++, Python, Qt, PyQt - training and consultancy > >"Programming in Python 3" - ISBN 0321680561 > >http://www.qtrac.eu/py3book.html > > ___ > > PyQt mailing listPyQt@riverbankcomputing.com > > http://www.riverbankcomputing.com/mailman/listinfo/pyqt > > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Rapid GUI Programming with Python and Qt
On Mon, 19 Jul 2010 15:06:12 +0200 (CEST) wrote: > Hello, > I would ike to have infos about the future new version for Python 3 > of this great book. Is there a publication date ? Hi "C", I would very much like to do a new edition of the PyQt book, but it will probably not be for another year or two due to other commitments. I want the next edition to be based on Python 3.1 (or later). Also, I am hoping that by the time I'm ready to start on it PySide will support Python 3 and will be sufficiently compatible with PyQt that I can cover both in the same book without confusing readers. For those who can't wait I have converted all the book's examples to Python 3.0 (using PyQt API 1) and to Python 3.1 (using PyQt API 2). I had expected the conversion to Python 3.1 and API 2 to be rather difficult, but in the end it was pretty straightforward, so the differences between what's shown in the book and the Python 3.1 versions of the examples are either non-existent or easy to see and understand. I've put a few notes on the most problematic classes at the bottom of the book's web page: http://www.qtrac.eu/pyqtbook.html (This is also where the links to the Python 3 examples are located.) On a personal note, last week I finished converting all my own Python programs to Python 3.1 using the 2to3 tool and then manually converting str % usage to str.format(). This includes some PyQt GUI programs that I use every day:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] best practices for MDI app
On 2010-07-15, Lic. José M. Rodriguez Bacallao wrote: > as dock widgets can only be placed in a main window, can I make an > internal main window as central widget of my main application windows > and then treat dock widgets in the central main window widget as my > display windows? this central main window doesn't have any central > widget at all. is this ok? [snip] It will probably work but I would consider it to be poor practice. Personally I'd create a custom QWidget subclass with exactly the desired behaviour rather than abuse a standard Qt widget:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] best practices for MDI app
On 2010-07-14, Lic. José M. Rodriguez Bacallao wrote: > how to view different windows at the same time using dock widgets? > We are developing a medical image viewer and we need to have the > possibility of viewing several images(series) at the same time. We > have tried MdiAre but it doesn't work nicely with vtk and I don't like > tab widgets. [snip] Dock widgets tend to be used for tool palettes so they are usually small in comparison to overall window size. Also, they can only be placed around the edges of the central area, so they are probably not ideal for your purpose. If you need to show a specific number of images (2, 3, 4) then a horizontal splitter might suffice (or two horizontal splitters laid out one above the other). -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] best practices for MDI app
On 2010-07-13, Danny Shevitz wrote: > Howdy, > > I'm a newbie and struggling with developing an MDI app. The basic question > is this: each of my documents > > looks and acts like a dialog. When I create my child class, should I > subclass QDialog or QWidget? > > I am currently using QDialog and add a QDialogButtonBox at the bottom. This > doesn't work as expected. > > When I click close, the MDI child blanks but doesn't disappear. It is as if > the QDialog is closing itself, > > but the MDI page still exists fine. If I subclass QWidget, then do I need > to reimplement all the button functionality? QDialog should only be used for dialogs (i.e., top-level windows). Use QWidget for MDI windows. Or better still use the new MDI classes: QMdiArea instead of QWorkspace and subclass QMdiSubWindow for the MDI windows themselves. Be aware that MDI has been out of fashion for several years so many people frown upon its use. The fashionable way to do things is to use a tab widget (which is utterly useless if you want to see two or more documents at the same time of course) and dock windows. If you need two or more windows visible and want to be fashionable then you can either use SDI (multiple top-level main windows -- which duplicate their menus and toolbars etc. of course) or use splitters. PS When you "close" a QDialog by default it is hidden not deleted. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] ProgressBar - Activity Mode
On 2010-07-13, Antonio Valentino wrote: > Hi list, > I would like to get a progress bar that works in a way similar to the > "Activity Mode" of the corresponding GTK widget: > > http://www.pygtk.org/pygtk2reference/class-gtkprogressbar.html#method-gtkpr > ogressbar--pulse > > i.e. show activity by a block moving back and forth within the progress > area. > > Is there a quick way to do it? > Some code snippet to grab? > > What are possible alternatives for this kind of task? Just set the minimum and maximum to 0 and you'll get exactly what you want. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] adding context menu to graphics item
On 2010-07-08, Christopher M. Nahler wrote: > I need some help on how to add a context menu to a graphics item. > > In the sample code below I have an action (editAction) on a menu > (myMenu) that is only enabled if a item is selected. > > Now I would like to have this menu show up as a context menu when I > right click the rect item in the scene/view. > > I think the way to do this is to do my own processing of the > contextMenuEvent. But what is the best way to do that? > > Store the menu in the scene so that I can access it from the > graphicsItem? And then do a menu.exec in the contextMenuEvent handler? > > Or are they better ways to do this? Is there some route with signalling? Hi Chris, Personally, I think you're doing the right thing in reimplementing the QGraphicsRectItem::contextMenuEvent() handler. In general I would always try to push the behaviour down to the relevant item itself. The alternative is doing things in the scene or view but that means you have to identify the item that is involved and adds complexity for no gain. So I'd just create a QMenu inside the contextMenuEvent() and go from there. PS Since you're using Python 3.1 you can replace all your super() calls that look like this: super(MyView, self).__init__(parent) with ones that look like this: super().__init__(parent) since Python 3 is a bit smarter than Python 2:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QTranslator and QFileDialog problems
On 2010-06-25, Eugen wrote: > I have some problems with translations of QFileDialog. In the example > below "dlg2" appears in English on my Windows XP development machine, > the rest in German. "dlg1" looks like a Qt custom dialog and "dlg2" > like the windows standard file dialog but with an old icon theme. On > other computers I have tested this (Ubuntu, Windows 7 and 2000) all > dialogs are in german. How can I get more information about what file > dialog Qt is using here and also what kind of theme is used there? > > import sys > from PyQt4.QtCore import * > from PyQt4.QtGui import * > > app = QApplication(sys.argv) > > qtTranslator = QTranslator() > if qtTranslator.load("qt_de", > QLibraryInfo.location(QLibraryInfo.TranslationsPath)): > app.installTranslator(qtTranslator) > > dlg1 = QFileDialog(None, "Dialog 1", ".", "All files (*.*)") > dlg1.open() > dlg2 = QFileDialog.getOpenFileName(None, "Dialog 2", ".", "All files > (*.*)") dlg3 = QMessageBox.question(None, > "Dialog 3", > "Frage?", > QMessageBox.Yes|QMessageBox.No| > QMessageBox.Cancel) > > sys.exit(app.exec_()) Hi Eugen, The rule of thumb is that Qt uses the native file dialog where one is available. As for the English vs. German Qt will respect the machine's locale unless you override it as you're doing here. So maybe you don't have the qt_de.qm file on your XP machine? You can tell Qt not to use native dialogs: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qfiledialog.html#Option- enum -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html I ordered a Dell netbook with Ubuntu... I got no OS, no apology, no solution, & no refund (so far) http://www.qtrac.eu/dont-buy-dell.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] binary file viewer with textEdit (PyQt) [correction]
On 2010-06-24, sandokan wrote: > Mark Summerfield-4 wrote: > > [snip] > > > > Actually I meant: > > file = QFile(self.filename) > > > > if file.open(QIODevice::ReadOnly): > > ba = file.readAll() # ba is a QByteArray filled with raw bytes > > hexbytes = [] > > > > for i in range(ba.count()): > > if QChar(" ") < QChar(ba[i]) < QChar(128): > > hexbytes.append(ba[i].toAscii()) > > > > else: > > hexbytes.append(ba[i].toHex()) > > # the above might need to be: > > # hexbytes.append(QByteArray(ba[i]).toHex()) > > # or even: > > # hexbytes.append(str(QByteArray(ba[i]).toHex())) > > > > self.ui.textEditAscii1.setPlainText("".join(hexbytes)) > > > > Still untested though! > > Hmm, this appending approach is very slow again :( Moreover, I need to be > able to print out also non-printable ASCII characters (0-32) and not to > show them as hex. > However thank you for you comments, I will try to think about different > solution...if you have any other idea then please let me know > > T. Well here's one last sketch of an idea (and this will work well no matter how big the file). - Create a plain QWidget and lay it out with a vertical scrollbar. - Set the QWidget's font to be fixed width. - Use QFontMetrics for the fixed width font to calculate how many characters wide the widget is and how many lines high. - Instead of reading the entire file, just read enough to occupy the space available and in the QWidget's paintEvent() use drawText() to draw them. - Set the scroll bar proportional to the size of the file and how much can be displayed. - If the user scrolls read in what's needed and repaint. This approach is a lot more work but potentially it could be very fast and also use the least amount of memory. Good luck! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] binary file viewer with textEdit (PyQt) [correction]
[snip] Actually I meant: file = QFile(self.filename) if file.open(QIODevice::ReadOnly): ba = file.readAll() # ba is a QByteArray filled with raw bytes hexbytes = [] for i in range(ba.count()): if QChar(" ") < QChar(ba[i]) < QChar(128): hexbytes.append(ba[i].toAscii()) else: hexbytes.append(ba[i].toHex()) # the above might need to be: # hexbytes.append(QByteArray(ba[i]).toHex()) # or even: # hexbytes.append(str(QByteArray(ba[i]).toHex())) self.ui.textEditAscii1.setPlainText("".join(hexbytes)) Still untested though! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] binary file viewer with textEdit (PyQt)
On 2010-06-24, sandokan wrote: > Mark Summerfield-4 wrote: > > One thing that slows QTextEdit down is its sophisticated layout engine. > > If you can live without that and use a QPlainTextEdit you should get > > some speedup straightaway. > > Wow, this works perfectly fine. However, I still have a problem with binary > file representation in a text field. Zeros (00h) are not visible at all > (zeros are not represented by white space as expected). So for example: > this: > "2E 64 6C 6C 00 4F 4C 45" (in hex) > should be represented as: > ".dll OLE" > but is represented as: > ".dllOLE" > > Maybe its because of chosen encoding but "mbcs" was only one which could > displayed binary file in QTextEdit at all: > s = codecs.open(self.filename,'rb','mbcs').read() > self.ui.textEditAscii1.setPlainText(s) > > Do you know any other encoding for binary files which could be used and > handled correctly by QTextEdit or should I change my approach completely > and try to display binary files other way? Personally, I wouldn't take that approach at all. If the file is binary then it isn't a text file so no encoding is correct. So I'd do something like this (untested): file = QFile(self.filename) if file.open(QIODevice::ReadOnly): ba = file.readAll() # ba is a QByteArray filled with raw bytes for i in range(ba.count()): if QChar(" ") < QChar(ba[i]) < QChar(128): ba[i] = ba[i].toAscii() self.ui.textEditAscii1.setPlainText(ba) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 http://www.qtrac.eu/pyqtbook.html A true story... I ordered a Dell netbook with Ubuntu preinstalled. It arrived with no OS at all and Dell's "support" said they don't supply Ubuntu any more. Dell gave no apology, no solution, and no refund. So I do *not* recommend Dell. ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Adding a layout to a QSlider widget
On 2010-06-23, V. Armando Solé wrote: > Hello, > > I am trying to create a widget consisting on a horizontal QSlider and an > additional widget at its side. The widget should behave as a QSlider. > > I have tried to do it inheriting from a QSlider but the problem is I > cannot get the additional widget at the side of the slider. It stays on > top. > > It can be observed with the example below. > > Why the added layout overwrites the QSlider? > > Is there something I am missing or I have to implement everything > starting from a QAbstractSlider? > > Thanks for your time. > > Best regards, > > Armando [snip] I wouldn't inherit QSlider: instead I'd inherit QWidget and aggregate a QSlider and a QLabel together: from PyQt4 import QtCore, QtGui class SliderWithBrowser(QtGui.QWidget): def __init__(self, *var, **kw): QtGui.QWidget.__init__(self, *var, **kw) self.slider = QtGui.QSlider() self.slider.setOrientation(QtCore.Qt.Horizontal) self.label = QtGui.QLabel(self) self.label.setText("This should not be on top of the Slider") # QVBoxLayout the label above; could use QHBoxLayout for # side-by-side layout = QtGui.QVBoxLayout() layout.setMargin(0) layout.setSpacing(2) layout.addWidget(self.label) layout.addWidget(self.slider) self.setLayout(layout) def test(args): app=QtGui.QApplication(args) w=SliderWithBrowser() w.show() app.exec_() if __name__=="__main__": import sys test(sys.argv) The above works fine for me. And you should be able to use SliderWithBrowser just like any other widget. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0321680561 http://www.qtrac.eu/py3book.html A true story... I ordered a Dell netbook with Ubuntu preinstalled. It arrived with no OS at all and Dell's "support" said the don't supply Ubuntu any more. Dell gave no apology, no solution, and no refund. So I do *not* recommend Dell. ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] using itemDoubleClicked with pyqt
Hi Chris, On 2010-06-23, Christopher M. Nahler wrote: > On 23.06.2010 09:46, Phil Thompson wrote: > > On Wed, 23 Jun 2010 09:40:09 +0200, "Christopher M. Nahler" [snip] > > The signal signature is "itemDoubleClicked(QListWidgetItem *)" > > > > Phil > > The way I understand this is that the signal passes a pointer to an > item, right? So what is the correct way to setup the connection? I have > tried with SIGNAL("itemDoubleClicked(item*)" and > SIGNAL("itemDoubleClicked(item *)" but that also did not work. The thing about using Qt signals is that you must specify the signal's _signature_, i.e., the type(s) it takes, but not their parameter names. This is a bit counter-intuitive for Python programmers since we're used to using parameter names not types. So, self.connect(self.myList, SIGNAL("itemDoubleClicked(*item)"), # WRONG self.processItem) must be written as: self.connect(self.myList, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.processItem) The quoted string inside SIGNAL must be the name of the signal and its parameter _types_. So for example, if you want to know when the current row has changed you'd write (assuming that self.myList is a QListWidget): self.connect(self.myList, SIGNAL("currentItemChanged(QListWidgetItem*,QListWidgetItem*)"), self.currentChanged) and the currentChanged method would look like this: def currentChanged(self, currentListItem, previousListItem): pass Hope that helps:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html A true story... I ordered a Dell netbook with Ubuntu preinstalled. It arrived with no OS at all and Dell's "support" said the don't supply Ubuntu any more. Dell gave no apology, no solution, and no refund. So I do *not* recommend Dell. ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] binary file viewer with textEdit (PyQt)
On 2010-06-22, sandokan wrote: > Hi, hope you can help me. I am trying to view whole contents of binary file > (PE file) in Qt TextEdit widget but still running into some problems (speed > is the main problem). I have tried these two ways: > 1) converting data using "codecs" > s = codecs.open(self.filename,'rb','mbcs').read() > self.ui.textEditAscii1.setPlainText(s) > - this kind of works but is very slowit take 10+ seconds to open 2kB > file > - reading is quite fast but displaying using setPlainText is tooo lazy > - I have also tried to append file line by line which was even slower > (hower I could at least process waiting events so the gui was not stuck > during the file load) . > - also zeros (00h) are not displayed at all (not even represented by a > white space) > > 2) displaying raw data which did not work at all: > file = open(fd.getOpenFileName(),'rb').read() > self.ui.textEditAscii1.setPlainText(file) > print file > - which prints file quite fine into console but displays only first ASCII > characters (actualy it displays "MZ" only) into textEdit widget > - using "self.ui.textEditAscii1.setPlainText(str(file))" did not change > anything > > Do you guys have any hint how to display larger binary files (let say up to > 10-20 MBs) in textEdit widget without waiting more than few seconds? Hi Tom, One thing that slows QTextEdit down is its sophisticated layout engine. If you can live without that and use a QPlainTextEdit you should get some speedup straightaway. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 http://www.qtrac.eu/aqpbook.html A true story... I ordered a Dell netbook with Ubuntu preinstalled. It arrived with no OS at all and Dell's "support" said the don't supply Ubuntu any more. Dell gave no apology, no solution, and no refund. So I do *not* recommend Dell. ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Master-detail relationship with plain QTableView tables (no SQL database)
On 2010-06-14, Vadym Honcharuk wrote: > thank you, Mark! > > one more question about applying filter in the context of > QSortFilterProxyModel: [snip] > > Question what method is analog of SQL setFilter() in context of > QSortFilterProxyModel? There are two approaches you can take with QSortFilterProxyModel. The easiest is to just create an instance and then use the setFilter*() methods. Alternatively, create a QSortFilterProxyModel subclass and reimplement filterAcceptsRow() returning True for rows that should be accepted and False for those that should be dropped. [snip] BTW I devote four chapters of my forthcoming book, "Advanced Qt Programming", to Qt's model/view classes---the book is C++-based but many of the concepts and idioms can easily be translated into PyQt. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QPlainTextEdit not created in a widget through a QAction
On 2010-06-07, Gerardo Gutierrez wrote: > Thanks Mark, I did some things that you recommended: Hi Gerardo, > I changed the notebook class, so it inherits from QWIdget and no container > need to be used, the notebook itself is going to be embedded in the > QScrollArea: > > class Notebook(QtGui.QWidget): > def __init__(self,parent): > QtGui.QWidget.__init__(self,parent) > ... > ... > self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) > self.new_cell_action=QtGui.QAction("new cell",self) > self.addAction(self.new_cell_action) That looks much better. > self.connect(self.new_cell_action,QtCore.SIGNAL("triggered(bool)"),self.new > _cell_slot) > > The new_cell_slot calls the function to create the a new cell, which has > not changed since last mail (I'm not calculation yet the size of the > cells). The problem persists even if I make the QAction parent to be the > notebook. The cell are appended in the _cell_list attribute but not showed > when the QAction is calling the new_input_cell function. I'd have to look at the whole code to figure that out and I don't have time... hopefully someone else will take a look! > This is a fragment of the main file: > > class IpythonQt(QtGui.QMainWindow,Ui_Qtipython): > def __init__(self): > QtGui.QMainWindow.__init__(self) > self.setupUi(self) > > self.scrollArea = QtGui.QScrollArea(self.centralwidget) > self.scrollArea.setWidgetResizable(True) > self.verticalLayout_2.addWidget(self.scrollArea) > self.nb=Notebook(self.scrollArea) > self.scrollArea.setWidget(self.nb) > self.nb.new_input_cell() This doesn't feel right to me. Personally, I really don't like using Qt Designer for QMainWindows, only for QDialogs and QWidgets. Also, QScrollArea should *not* be inherited. It is a rare exception in Qt of a class designed to be used as is and never inherited. (If you want inheritance use QAbstractScrollArea---but don't bother it is pain for little gain.) Anyway, back to the point. I am assuming that self.centralwidget is the main window's central widget. If that is the case, then putting it into a scroll area is wrong. If your Notebook is the thing that belongs in the middle (as I suspect it should since anything else can go inside dock widgets), then I'd expect to see code like this: self.nb = Notebook() self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.nb) self.setCentralWidget(self.scrollArea) OTOH if you have a whole bunch of widgets in the middle and the Notebook is just one of them, then I'd expect to see: self.nb = Notebook() self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.nb) self.verticalLayout_2.addWidget(self.scrollArea) (BTW Only give parents to things that are not put in a layout.) I also don't like the call to self.nb.new_input_cell() in __init__(). You should use __init__() to create all the things the GUI uses, but _not_ to make use of them. If you want to perform some action when everything is set up then put it in a slot and at the end of __init__() use something like this: QTimer.singleShot(0, self, SLOT(initialize)) and in your initialize() method do self.nb.new_input_cell() etc. Sorry I couldn't see the answer to your problem, but hope the other comments prove helpful! [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Problem with printing to pdf
On 2010-06-07, mille kink wrote: > Dear, > > I'm creating an application where there are several pdf's being > created in batch. > As far as creating the pdf's there is no problem, all is working smooth. > > Im using a QWebview to build up the document and then print it to a > QPrinter > > > But now comes the question. Is there a signal to attach to a QPrinter > to know when the printing is done or is there any way of knowing > when the printer is done, so I can start the next file. > > Hopefully this is not a to stupid question but I've been searching the > net and could not find an answer. I'm not aware of any signal that will tell you this, so I'd suggest polling QPrinter.printerState(). -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QPlainTextEdit not created in a widget through a QAction
Hi Gerardo, I'm not sure I can help but have a few comments... On 2010-06-06, Gerardo Gutierrez wrote: > Hi, I'm writing a frontend for ipython and I've a problem with a context > menu... > The frontend is based on mathematica so it has cells when you can write > code and execute it (not yet implemented) > So the cells are QPlainTextEdits which are embedded in a QWidget: > > class Notebook(QtCore.QObject): > def __init__(self,parent): > QtCore.QObject.__init__(self) > self._container=QtGui.QWidget(parent) > self._nb_menu=NbContextMenu(self._container) I don't really understand why Notebook doesn't inherit QWidget directly. > self.connect(self._nb_menu.new_cell,QtCore.SIGNAL("triggered(bool)"),self.n > ew_cell_slot) self._container.mousePressEvent = self.nb_mouse_click_event > > so the last line is for the context menu to popup con right click: > > def nb_mouse_click_event(self,event): > if event.button()==QtCore.Qt.RightButton: > self._nb_menu.popup(event.globalPos()) Do you really need to implement such a low-level event handler? If Notebook inherits QWidget rather than QObject you can set its context menu policy either to Qt.ActionsContextMenu (in which case you can add the actions directly to the Notebook using addAction()), or to Qt.CustomContextMenu (in which case you connect the customContextmenuRequested() signal to a slot where you create the context menu yourself). > The NbContextMenu class is described here: > > class NbContextMenu(QtGui.QMenu): > def __init__(self,parent): > QtGui.QMenu.__init__(self,parent) > self.set_actions() > > def set_actions(self): > self.new_cell=QtGui.QAction("new cell",self) > self.addAction(self.new_cell) I don't understand why you need this class. If Notebook is a QWidget you can use one of the techniques I mentioned above. But if it is a QObject then why not use a plain QMenu and use its addAction() method to add actions to it directly? > The connection showed above calls a slot which calls a function to create a > new cell in the QWidget called _container: > > def new_input_cell(self,index=0): > cell=InputCell(self._container) > if index==0: > prev_cell=self._cell_list[len(self._cell_list)-1] > > cell.setGeometry(QtCore.QRect(0,prev_cell.pos().y()+prev_cell.height()+5,39 > 5,60)) self._cell_list.append(cell) > else: > prev_cell=self._cell_list[index-1] > > cell.setGeometry(QtCore.QRect(0,prev_cell.pos().y()+prev_cell.height()+5,39 > 5,60)) self._cell_list.insert(index,cell) >cell.index=self._cell_list.index(cell) >self.connect(cell,QtCore.SIGNAL("cell_index"),self.active_cell_signal) > > self.connect(cell,QtCore.SIGNAL("blockCountChanged(int)"),self.expand_cell > ) Using hard-coded numbers will make the application fragile. You might get away with little tweaks like +5, but for the 39 and 60 it would be better to compute them, for example based on QApplication.globalStrut(). > The problem is then, that through the QMenu QAction the cells are being > appended but not showed. This doesn't happen if I call the function > new_input_cell from the constructor in the mainwindow class. I don't know why, but I am suspicious that you have made the QAction's parent be the QMenu; I would try making the QAction's parent the QWidget the QMenu is associated with (e.g., the Notebook if you change it to be a QWidget or self._container otherwise). Good luck! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Master-detail relationship with plain QTableView tables (no SQL database)
On 2010-06-05, Vadym Honcharuk wrote: > works excellent! Thanks a lot! :-D > one question almost on this issue: only one QDataStream may exist per > one file? May be one more approach is separate QDataStream for each > tables and in one file? Yes, only *one* QDataStream per file! If you wanted to handle the tables separately then one possible approach would be to do something along these lines: open a QDataStream on a QBuffer for table #1 open another QDataStream on another QBuffer for table #2 write the data but this time to each table's associated buffer once the buffers have been written to, close them and then open a QDataStream to the file & write the buffers to the file one after the other and reverse for reading However, this is more complicated and means that you store the entire file's worth of data in memory (in addition to the data in the tables) at once, so I prefer writing to the file directly using a single QDataStream. [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Master-detail relationship with plain QTableView tables (no SQL database)
On 2010-06-05, Mark Summerfield wrote: > On 2010-06-05, Vadym Honcharuk wrote: > > Thanks a lot, Mark! > > Hi Vadym, > > One approach that you could take is to write the count of how many > things you're going to write and then write the things. For example, > you could try something like this: > > write data: > > srcCount = self.srcTableModel.count() Ooops, I meant .rowCount() not .count() throughout of course! [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3 (Second Edition)" - ISBN 0321680561 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Master-detail relationship with plain QTableView tables (no SQL database)
On 2010-06-05, Vadym Honcharuk wrote: > Thanks a lot, Mark! Hi Vadym, One approach that you could take is to write the count of how many things you're going to write and then write the things. For example, you could try something like this: write data: srcCount = self.srcTableModel.count() stream.writeInt32(srcCount) # NEW for row in range(srcCount): # write the row as before frmCount = self.frmTableModel.count() stream.writeInt32(frmCount) # NEW for row in range(frmCount): # write the inner row as before read data: self.srcTableModel.ships = [] self.frmTableModel.ships = [] srcCount = stream.readInt32() # NEW for srcRow in range(srcCount): if stream.atEnd(): # handle error equipment = QtCore.QString() stream >> equipment srcCode = stream.readInt32() srcName = QtCore.QString() stream >> srcName self.srcTableModel.ships.append(srcShip(equipment, srcCode, srcName)) frmCount = stream.readInt32() # NEW for frmRow in range(frmCount): if stream.atEnd(): # handle error formationSrcName = QtCore.QString() stream >> formationSrcName evolvingGasDepletion = stream.readInt32() evolvingGasTemperature = stream.readInt32() ... [snip] I hope this helps! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QTableWidget: cannot alter text of header labels
On 2010-05-20, Nick Gaens wrote: > Hello PyQt, > > I'm wondering why I can't change the text that's displayed in the > horizontal or vertical header of my standard QTableWidget. > > - Constructor and simple count specification > > self.tw = QtGui.QTableWidget() > > self.tw.setColumnCount(5) > > - Attempt 1: > > self.tw.setHorizontalHeaderLabels(("a", "b", "c", "d", "e")) # Doesn't > > work, the default "1" ... "5" are still shown Try passing a list not a tuple, i.e., self.tw.setHorizontalHeaderLabels(["a", "b", "c", "d", "e"]) # works for me -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Master-detail relationship with plain QTableView tables (no SQL database)
On 2010-05-20, Vadym Honcharuk wrote: > 2010/5/9 Mark Summerfield : [snip] > Thank you, Mark! > > One more question in this issue is how to save data from these three > tables with different models in one file by QDataStream module. The > point of problem in that save method calling from their models itself > and if I have three models - every will try open same file and save > data in series? But seems this is not too correct desicion... > > With best rgards, > -vadym Hi Vadym, There are many possible approaches to this. One approach is to make just one of the models (or a new "ModelManager" class) responsible for saving. This class would be the only one that had a save method and would work somewhat like this: open the file for each row in the "main" model: write the row's data for each row in the "sub" model that corresponds to main data's row: write the sub model row data # and if there's a sub-sub model iterate over the sub-sub # model's rows that correspond to the sub model's rows # and if there's more than one sub model, iterate over each # one's corresponding rows & write their data Other approaches are equally valid. For example, you could save one file per model which is the simplest and probably the most maintainable approach---and the one that I personally prefer. Nor is saving each model's data in series necessarily bad---but it does require you to synchronize and is more risky than the other two approaches I've mentioned. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Performance problems with QSortFilterProxyModel
On 2010-05-12, Steve Borho wrote: > On Wed, May 12, 2010 at 1:04 AM, Mark Summerfield wrote: > > On 2010-05-12, Steve Borho wrote: > >> Hello, > >> > >> The TortoiseHg project is currently porting all of our PyGTK apps to > >> PyQt, This has been going pretty well so far, but I've hit a snag with > >> our file status browser. > >> > >> I have a simple QAbstractTableModel (4 columns) being displayed in a > >> QTreeView. After connecting a QSortFilterProxyModel between the tree > >> view and the data model, reloading the model became very expensive for > >> moderately sized data sets. After calling setSourceModel() with a > >> model of 555 rows, I counted over 3 million calls to the model data() > >> method, which takes about 15 seconds. > > > > Have you tried switching off sorting just before resetting the model and > > then switching it back on afterwards? > > I just tried with this: > > tm = MyTableModel(data) > tv.setSortingEnabled(False) > proxy.setSourceModel(tm) > tv.setSortingEnabled(True) > > But it made no performance difference. Then maybe no sorting took place? When you call QAbstractTableView.setSortingEnabled(True), Qt is supposed to call QAbstractTableView.sortByColumn() to perform the sort. But sortByColumn() will only have an effect if the model is sortable, that is, if the QAbsractItemModel you're using has reimplemented the sort() method (since the base class version does nothing). Things are slightly different if you use a QSortFilterProxyModel of course, since that provides an implementation of QAbsractItemModel.sort(). So in the example you've shown the proxy should do the sorting. But I guess you're saying "yes it sorted---but it was just as slow"? However, you don't mention where the model gets set on the view? Does this make a difference: # tv has no model at this point tm = MyTableModel(data) tv.setSortingEnabled(False) proxy.setSourceModel(tm) tv.setModel(proxy) # now tv has a model tv.setSortingEnabled(True) Using QSortFilterProxyModel can adversely affect performance. So one solution is to try to avoid using it, i.e., by reimplementing the sort() method in your custom QAbstractTableModel. Another solution is to get the correct ordering without sorting at all by using intrinsically ordered data structures. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Performance problems with QSortFilterProxyModel
On 2010-05-12, Steve Borho wrote: > Hello, > > The TortoiseHg project is currently porting all of our PyGTK apps to > PyQt, This has been going pretty well so far, but I've hit a snag with > our file status browser. > > I have a simple QAbstractTableModel (4 columns) being displayed in a > QTreeView. After connecting a QSortFilterProxyModel between the tree > view and the data model, reloading the model became very expensive for > moderately sized data sets. After calling setSourceModel() with a > model of 555 rows, I counted over 3 million calls to the model data() > method, which takes about 15 seconds. Have you tried switching off sorting just before resetting the model and then switching it back on afterwards? [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3 (Second Edition)" - ISBN 0321680561 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Master-detail relationship with plain QTableView tables (no SQL database)
On 2010-05-08, Vadym Honcharuk wrote: > Hi to All, > > I need three tables with master-detail relationship one to other. I > made QTableView Model from Mark book and three vertical frame on one > page for it. How possible connect these tables with master-detail > relationship? Examples are really welcome if possible... Hi Vadym, My book shows how to do master-detail in the context of a SQL database (e.g. pp. 463), but the same technique can be applied to any pair of table models. One approach is to connect the master table's selectionModel()'s currentRowChanged(QModelIndex,QModelIndex) signal to a custom slot. Then, in the custom slot you handle the populating of the detail table, for example, by filtering (which you can do with a sort/filter proxy model). -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt book: examples now available for Python 3.1 + PyQt API 2
On 2010-04-29, Jean-Claude Repetto wrote: > Le 29/04/2010 10:54, Mark Summerfield a écrit : > > I've now ported the PyQt book's examples to Python 3.1 and PyQt's API 2. > > Hi Mark, > > Will you publish soon a new edition of the book, based on Python 3 and > PyQt's API 2 ? Hi Jean-Claude, I'm just finishing a new C++/Qt book "Advanced Qt Programming" at the moment. I plan to start a new book in October. I have a short list of three I'd like to write, and a new PyQt book is on the list. I'll will decide on which one to do over the summer. I want to see how far PySide gets, particularly regarding Python 3, since I want the next edition to use Python 3.1 and API 2, and ideally cover both PyQt and PySide (providing they are compatible enough not to cause a lot of confusion). Whether I do it as my next book or as a later one, if I do a second edition it will probably have a new title (to reflect coverage of PySide and PyQt), and I plan to drop Part I (Python Programming). That will leave room for me to increase the coverage of GUI programming (and will hopefully encourage people to buy my Python 3 book:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] PyQt book: examples now available for Python 3.1 + PyQt API 2
Hi, I've now ported the PyQt book's examples to Python 3.1 and PyQt's API 2. The examples do _not_ take any advantage of Python 3.1 features (except for str.format()), or of any Qt features beyond Qt 4.2 which is the version the book is based on. See the very bottom of this web page for the download links: http://www.qtrac.eu/pyqtbook.html -- Here are some notes on my experience of doing the porting: I ported to Python 3.1 _first_, and then once that was working I replaced str % with str.format(), and only then I ported to API 2. I had to make changes to the code in relation to the following classes: QDataStream QSettings QString QTextStream QVariant To read/write QStrings (which don't exist in API 2) using QDataStream you must use QDataStream.readQString() and QDataStream.writeQString(). (Do _not_ use QDataStream.readString()/QDataStream.writeString() for strings; use them for QByteArrays, bytes, and bytearrays.) I did not find any way to read/write bools from/to QSettings. (But I didn't spend a lot of time on this.) My solution was to store int(0) and int(1) instead: settings = QSettings() settings.setValue("Happy", 1) ... happy = bool(int(settings.value("Happy"))) You can't just do bool(settings.value()) of course since QSettings seems to store basic Python types as strings and bool("0") is True---whereas bool(int("0")) == bool(0) == False. I discovered that I'd often used QString methods such as .endsWith(), .isEmpty(), .indexOf(), .lastIndexOf(), .mid(), .left(), .right(), and .trimmed(). All these are easy to change with equivalent str methods. The only real differences when using QTextStream were when reading since you now get back strs rather than QStrings so must use str rather than QString methods if you want to process them. In a few places I'd used QVariant.to*() methods, e.g., QVariant.toDate(); these are no longer needed since when API 2 is in use PyQt automatically converts to/from QVariant. Overall I was pleasantly surprised at how straightforward the porting was (although I didn't do much testing!). API 2 code is cleaner and clearer than API 1 code---and more Pythonic with the use of str instead of QString and the elimination of QVariant. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Converting to API 2
On 2010-04-22, detlev wrote: > On Donnerstag, 22. April 2010, Mark Summerfield wrote: > > Hi, > > > > I'm starting to convert the examples from my PyQt book to Python 3 with > > API 2. Perhaps I'm not awake yet, but I'm puzzled by this: > > > > Python 3.1.2 (r312:79147, Mar 25 2010, 07:42:02) > > [GCC 4.4.1] on linux2 > > Type "copyright", "credits" or "license()" for more information. > > > > >>> from PyQt4.QtCore import * > > >>> from PyQt4.QtGui import * > > >>> PYQT_VERSION_STR > > > > '4.7.3' > > > > >>> QT_VERSION_STR > > > > '4.6.1' > > > > >>> fh = QFile("/tmp/data") > > >>> fh.open(QIODevice.WriteOnly) > > > > True > > > > >>> out = QDataStream(fh) > > >>> out.writeString("hello") > > > > Traceback (most recent call last): > > File "", line 1, in > > out.writeString("hello") > > TypeError: QDataStream.writeString(str): argument 1 has unexpected > > type 'str' > > This should be > > >>> out.writeString("hello".encode()) > > i.e. it must be converted to a bytes object. Ah, thank you! So basically, the docs which say QDataStream.writeString(str) assume that str is a Python 2 string not a Python 3 string even for API 2:-( > > And also by this: > > >>> fh = QFile("/tmp/data") > > >>> fh.open(QIODevice.WriteOnly) > > > > True > > > > >>> out = QDataStream(fh) > > >>> out << "hello" > > You should use writeString(). When I ported eric to Python3, I stumbled > over both these issues. Oh, sure, I just showed that because it looked like the same problem. Thanks! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] Converting to API 2
Hi, I'm starting to convert the examples from my PyQt book to Python 3 with API 2. Perhaps I'm not awake yet, but I'm puzzled by this: Python 3.1.2 (r312:79147, Mar 25 2010, 07:42:02) [GCC 4.4.1] on linux2 Type "copyright", "credits" or "license()" for more information. >>> from PyQt4.QtCore import * >>> from PyQt4.QtGui import * >>> PYQT_VERSION_STR '4.7.3' >>> QT_VERSION_STR '4.6.1' >>> fh = QFile("/tmp/data") >>> fh.open(QIODevice.WriteOnly) True >>> out = QDataStream(fh) >>> out.writeString("hello") Traceback (most recent call last): File "", line 1, in out.writeString("hello") TypeError: QDataStream.writeString(str): argument 1 has unexpected type 'str' And also by this: >>> fh = QFile("/tmp/data") >>> fh.open(QIODevice.WriteOnly) True >>> out = QDataStream(fh) >>> out << "hello" Traceback (most recent call last): File "", line 1, in out << "hello" ValueError: string of length 1 expected What am I missing here? -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3 (Second Edition)" - ISBN 0321680561 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Threading crashes
On 2010-04-20, andre hotz wrote: > Mark Summerfield schrieb: > > On 2010-04-20, andre hotz wrote: > >> Hey, > >> > >> I have a problem with my QThreads (running on windows). It is the first > >> time I use multithreading, so I am probably doing something wrong ;) > >> > >> The situation is as follows: I have a QTreeWidget which works like a > >> filebrowser, listing a few thousand files. Creating > >> the treeitems from the files is pretty fast, but I also want the > >> treeWidget to display more information about the files. > >> This is taking some time depending on the quantity of the files. So what > >> I did is to first fill the treeView with all the filenames. > >> After that, I start an update-threat, which loops through all the items > >> in the treeWidget, gathers its data and fills the additional > >> columns in the treeView with the data. While the thread is updating the > >> treeWidget, the user can already work with the files and does not need > >> to wait for the update to finish. > >> > >> This all works pretty well. > > > > I think you've been pretty lucky to have it work at all! > > hehe, yeah, I was pretty happy when I got it working the first time ;) > > > Qt does not provide any means of locking items or views. As a > > consequence, Qt does _not_ support updating models, scenes, or items in > > models, or items in widgets such as QTreeWidgetItems or > > QTableWidgetItems, etc. outside the main (GUI) thread. So any such > > update is potentially the source of a crash. > > hm, yes, this might explain the crashes.. > > > One technique that could be used is to hold the data in a thread-safe > > data structure and read data from that into the GUI as needed (locking > > the data structure or each item read from it as needed), and updating > > the data from one or more secondary threads (locking as needed). > > That sounds like it could work. Would it be possible to hold the data as > you said, but when the update thread is finished, let it emit a signal > to the treeWidget which then updates itself with the given data > structure? Or does emitting signals from another thread also not work? One of the great things about signals and slots is that they work safely across threads:-) So you can certainly emit a signal in a secondary thread that's connected to a main (GUI) thread slot. And since you can pass values via signals, if you had simple things like ints, doubles, and QStrings, you could even call the main thread every time you updated the data on a single file in the secondary thread (at some cost in performance that may or may not matter) to give the main thread the info you want. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Render ps files
On 2010-03-05, Matt Smith wrote: > Is there a way to render ps (postscript) files, to a pixmap, or QImage? > Something I could display in a widget at least. > > thanks > mbs I don't think there's anything built in to PyQt to do this. However, you could use ghostscript to convert PS to PDF and then use the Qt version of the poppler library to render the PDF pages to QImages. (I've done this in C++/Qt and believe that there is a Python wrapper for poppler, but I haven't used it.) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QAbstractItemModel's "dataChanged" signal not working?
On 2010-02-27, Claudio Felix wrote: > Hi everyone, > > I'm using a QSqlRelationalTableModel for a simple dialog where I can > add/delete periods related to a particular customer, which is chosen > by a QComboBox. The periods table is filtered by customer (whose ID is > a foreign key) and shown through a QTableView. There's an "Add" button > which basically inserts a new row in the Periods table and sets the > view to edit mode, so the period data can be entered: > > def addRecord(self): > row = self.model.rowCount() > customerid = self._getRecordID(self.customerComboBox, > self.customersModel, "CUSTOMER_ID") > self.enableControls(False) > self.model.insertRow(row) > index = self.model.index(row, CUSTOMER_ID) > self.model.setData(index, QVariant(customerid)) > index = self.model.index(row, PERIOD_YEAR) > self.periodsTableView.setCurrentIndex(index) > self.periodsTableView.edit(index) > > I noticed that, while the view is in edit mode (with the asterisk '*' > appearing in the leftmost field), if the user clicks on the add button > again, an empty row appears in the view and the asterisk appears in > the next row, with this message on the console: > > edit: index was invalid > edit: editing failed > > The same problem happens in the "assetmanager.pyw" example from the > (great!) book "Rapid GUI Programming with Python and QT", which is my > main guide. That way, in my limited experience with PyQT, I tried to > work around the undesirable behavior creating the method > "enableControls" for the dialog, which is called in the addRecord > method so it makes it impossible for the user to click on "add" again > while the view is in edit mode. The idea then was to re-enable the > controls when the data was finally committed by the view. That's when > the main problem comes up. I tried to use the model's "dataChanged" > signal for calling my "enableControls" method, but it looks like it > never gets emitted, although the record does get written to the > database table. Does anybody can confirm that or help me avoiding the > problem at all? I used the following signature for the signal, exactly > the same shown on QAbstractItemModel's documentation: > > self.connect(self.model, SIGNAL("dataChanged(const QModelIndex&,const > QModelIndex&)"), self.enableControls) > > That line is declared in my dialog's __init__, along with all the > other (working) signals. self.model referes to the > QSqlRelationalTableModel. > > Thanks for any help! Hi Claudio, I must admit that I've grown very frustrated with Qt's database support, particularly with SQLite. I've found that the book's database examples (which all use SQLite since that is supplied with Qt) exhibit varying differences in behavior depending on the Qt version. Regarding your specific problem, I can't see anything obviously wrong with your connection. Personally, I would have written it as self.connect(self.model, SIGNAL("dataChanged(QModelIndex,QModelIndex)"), self.enableControls) but that should make no difference. Is your model a QSqlRelationalTableModel or a subclass? If it is a subclass and you have reimplemented setData() then you must emit the dataChanged() signal in your reimplemented setData() method. But if you're using QSqlRelationalTableModel directly then it isn't obvious to me what you're doing wrong. However, dataChanged() might be the wrong signal for reenabling the Add button since it is emitted for every change to every field, whereas I'd have thought you wanted to enable the Add button only when the record was inserted? So maybe you could try connecting to the QAbstractItemModel::rowsInserted() signal? I had a quick go at changing assetmanager.pyw to do this but without success (using PyQt 4.6 and Qt 4.5.2); maybe things have improved with Qt 4.6. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] problems with PyQt book custom view examples [Win7]
On 2009-12-17, Simon Hibbs wrote: > Romi Agar: > >I seem to be experiencing some problems with custom view examples in PyQt > >book. > > > >I'm running Win 7 x64, Python 2.6.4rc2, PyQt 4.6.2. > > Are you using the latest errata and several fixed and updated versions of > the complete source code for the examples? These are available from the > main book site: > > http://www.qtrac.eu/pyqtbook.html > > I don't think any of these have been tested on Windows 7, at least there's > no indication of it, let alone the x64 version. Phil also replied to this saying, "make sure PyQt is built with SIP 4.9.3". But you are quite right: none of the examples has been tested with Windows 7 or on 64-bit machines (at least not by me, since I don't have Windows 7 or a 64-bit machine---hopefully that'll change next summer). -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] problems with PyQt book custom view examples [Win7]
On 2009-12-08, Romi Agar wrote: > For example chapter 6: imagechanger_ans.pyw. It remebers the window size > and log window position, but not the last accessed images. > I think that this has something to do with using QStrings. > I just tested the chapter 16 carhirelog.pyw example. By default it does not > show the content of License, Customer and Notes columns. But what do they > have in common? In CarHireLog class, they are all stored as QStrings. > Removing the conversion to QString from the initializer and voilaa - it > works. Maybe the recent files problem comes also from QString usage or > QStringList conversion - haven't tested yet. Ah, okay, it sounds like you're on the right track. Maybe your PyQt is using API 2 rather than API 1---all the examples only work for API 1 (which was the only API that existed when the book was written). But API 2 is not supposed to be the default for Python 2 and you say you're using Python 2.6... > > > 2009/12/8 Mark Summerfield > > > On 2009-12-08, Romi Agar wrote: > > > Everything else seems to be working apart from the little bug with > > > saving application settings to Windows registry. It does "remember" > > > the application size and position, but recently used files do not get > > > loaded when the program is relaunched. I checked, that recently used > > > program data gets written to the registry (at least some kind of byte > > > array) on application termination, but somewhere in the application > > > loading process it gets lost or is not recognised. > > > > In which particular example(s) does that occur? > > > > > 2009/12/8 Mark Summerfield > > > > > > > On 2009-12-08, Romi Agar wrote: > > > > > Hi! > > > > > > > > > > I seem to be experiencing some problems with custom view examples > > > > > in PyQt book. I'm running Win 7 x64, Python 2.6.4rc2, PyQt 4.6.2. > > > > > The problem is with chapter 14 and 16 custom view applications. > > > > > When run, they show empty tables (no visible data) with different > > > > > background color shades on some rows. The Chapter 16 waterquality > > > > > example has an empty table with 17508 rows. Does someone maybe know > > > > > a solution to this problem? > > > > > > > > I just tried all the examples in those chapters with: > > > > - Python 2.6.2, Qt 4.5.3, PyQt 4.5.1, Linux 32-bit > > > > - Python 2.6.4, Qt 4.5.3, PyQt 4.6.2, Windows XP 32-bit > > > > and they ran fine. (I ran them from the console from their own > > > > directories.) > > > > > > > > I don't have Windows 7, so can't test on your platform. > > > > > > > > If the problem is with Qt, it might take a while before it is fixed > > > > since Windows 7 is a "Tier 2" platform for Qt 4.6 (should be Tier 1 > > > > for Qt 4.7), so bugs in Qt for Windows 7 may not get high priority > > > > yet. http://doc.trolltech.com/4.6/supported-platforms.html > > > > > > > > I haven't heard of other people having problems like this with > > > > Windows > > > > 7 > > > > > > though---at least not yet. And it is hard to know what the problem > > > > really > > > > > > is, let alone suggest a solution. Do the other examples work okay? > > > > > > > > -- > > > > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > > > >C++, Python, Qt, PyQt - training and consultancy > > > >"Advanced Qt Programming" - ISBN 0321635906 > > > > -- > > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > >C++, Python, Qt, PyQt - training and consultancy > >"Advanced Qt Programming" - ISBN 0321635906 > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3 (Second Edition)" - ISBN 0321680561 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] problems with PyQt book custom view examples [Win7]
On 2009-12-08, Romi Agar wrote: > Everything else seems to be working apart from the little bug with > saving application settings to Windows registry. It does "remember" > the application size and position, but recently used files do not get > loaded when the program is relaunched. I checked, that recently used > program data gets written to the registry (at least some kind of byte > array) on application termination, but somewhere in the application > loading process it gets lost or is not recognised. In which particular example(s) does that occur? > 2009/12/8 Mark Summerfield > > > On 2009-12-08, Romi Agar wrote: > > > Hi! > > > > > > I seem to be experiencing some problems with custom view examples in > > > PyQt book. I'm running Win 7 x64, Python 2.6.4rc2, PyQt 4.6.2. The > > > problem is with chapter 14 and 16 custom view applications. When run, > > > they show empty tables (no visible data) with different background > > > color shades on some rows. The Chapter 16 waterquality example has an > > > empty table with 17508 rows. Does someone maybe know a solution to > > > this problem? > > > > I just tried all the examples in those chapters with: > > - Python 2.6.2, Qt 4.5.3, PyQt 4.5.1, Linux 32-bit > > - Python 2.6.4, Qt 4.5.3, PyQt 4.6.2, Windows XP 32-bit > > and they ran fine. (I ran them from the console from their own > > directories.) > > > > I don't have Windows 7, so can't test on your platform. > > > > If the problem is with Qt, it might take a while before it is fixed > > since Windows 7 is a "Tier 2" platform for Qt 4.6 (should be Tier 1 for > > Qt 4.7), so bugs in Qt for Windows 7 may not get high priority yet. > > http://doc.trolltech.com/4.6/supported-platforms.html > > > > I haven't heard of other people having problems like this with Windows 7 > > though---at least not yet. And it is hard to know what the problem really > > is, let alone suggest a solution. Do the other examples work okay? > > > > -- > > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > >C++, Python, Qt, PyQt - training and consultancy > >"Advanced Qt Programming" - ISBN 0321635906 > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Moving from Python 2 to Python 3: A 4 page "cheat sheet"
On 2009-12-01, Glenn Linderman wrote: > On approximately 12/1/2009 6:15 AM, came the following characters from > > the keyboard of Mark Summerfield: > > Here's the direct link: > > http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > Produces "File not found." in a web page, when I click. The link seems to have been mangled. Here it is in full: http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Advanced Qt Programming" - ISBN 0321635906 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] Moving from Python 2 to Python 3: A 4 page "cheat sheet"
Hi, I've produced a 4 page document that provides a very concise summary of Python 2<->3 differences plus the most commonly used new Python 3 features. It is aimed at existing Python 2 programmers who want to start writing Python 3 programs and want to use Python 3 idioms rather than those from Python 2 where the idioms differ. It uses Python 3.1 syntax since that looks like being the standard for a few years in view of the language moratorium. The document is U.S. Letter size but will also print fine on A4 printers. It is available as a free PDF download (no registration or anything) from InformIT's website. Here's the direct link: http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... And of course, if you want more on Python 3, there's always the documentation---or my book:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3 (Second Edition)" - ISBN 0321680561 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Problem with class inheriting QDialog
On 2009-11-20, dizou wrote: > Dialog.py: > > import sys > from PyQt4.QtGui import QDialog > > def Dialog(QDialog): I assume that's a typo above and that you've really got: class Dialog(QDialog): > def __init__(self, parent): > QDialog.__init__(self, parent) > > MainWindow.py: > > from PyQt4.QtCore import SIGNAL, SLOT, QDir, QFile > from PyQt4.QtGui import QApplication, QMainWindow, QMenu, QMessageBox, \ > QWidget, qApp, QAction, QFileDialog, QPushButton > from Dialog import * > > class MainWindow(QMainWindow): > def __init__(self): And as David Douard mentioned, you must do super().__init__(self) # or similar > #stuff > self.editButton = QPushButton(self) > self.connect(self.editButton, SIGNAL("clicked()"), > self.EditButtonClicked) > def EditButtonClicked(self): > self.dialog = Dialog(self) > print type(self.dialog) > self.dialog.exec_() > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3 (Second Edition)" - ISBN 0321680561 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] need drawing application demo
On 2009-11-19, Mitchell Model wrote: > I am just starting to do serious work with PyQt, having used many > other GUI/widget toolkits over the years. The rich collection of demos > and examples included in the installation -- apparently a large subset > of the ones in the Qt installation -- is impressive and very helpful. > I am surprised, however, by the absence of what to me is the canonical > demonstration, and one that I often program as my first exercise in a > new toolkit: a small drawing program. The program should offer a > palette of shapes (including lines), with the ability to place, move, > resize, delete, and duplicate a shape. Optional features like > specifying the color or size of the border and the color of the fill > are good too. Grouping, locking, anchoring lines to shapes, and Undo/ > Redo/History would be even better. > > Surely a demo like this exists somewhere? Could someone point me to > one? (I am aware of the Diagram Scene example. It has some of what I > am looking for, but apparently no way to resize shapes using the > standard maneuver of grabbing a handle or corner and dragging). With Qt you really have two different ways you can implement a drawing program. One way is to create your own in-memory data structures and create a QWidget subclass where you paint everything yourself. Another way is to create a QGraphicsScene and populate it with QGraphicsItems. Which is best rather depends on what you want to achieve, although I think that using QGraphicsScene is easier. I present an example that does some of the things you're talking about in my PyQt book (chapter 13's Page Designer---in particular pagedesigner_ans.pyw). It uses QGraphicsScene and should be easy to extend to do all the things you mention. The book's examples can be downloaded from my web site. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Stacking QWidgets vertically?
On 2009-09-21, Mark Summerfield wrote: > On 2009-09-21, Kurt Schwarz wrote: > > A QSplitter isn't what I am looking for because "A splitter lets the > > user control the size of child widgets by dragging the boundary > > between the children." I don't want the user to be able to re-size the > > widgets, sorry if I wasn't clear about this before. > > > > Here is a picture to better illustrate what I am looking for: > > http://img89.imageshack.us/img89/8837/83828522.png > > > > In this example I have to set the x, y cords manually im looking for > > something more automated as those boxes are generated with dynamic > > heights. > > Using a QVBoxLayout seems reasonable to me. > > Suppose your widgets are: > > widget1 = QWidget() # could be a dummy widget (this will occupy > # the big red area) > widget2 = ... # this is the one that is about 1/2 as tall as the > # other two > widget3 = ... # one from bottom > widget4 = ... # bottom > > You might find this works (untested): > > layout = QVBoxLayout() > layout.addWidget(widget1, 10) # these ints are stretch factors > layout.addWidget(widget2, 1) # they say how much space the widgets > layout.addWidget(widget3, 3) # should get in proportion to each > layout.addWidget(widget4, 2) # other > > You can also set minimum sizes (e.g., heights) & size policies for the > widgets---all of which should be enough to get what you want. > > (I missed any earlier emails, so sorry if you've already tried this.) > -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Problem with boundingRect in PyQt snapshot
On 2009-09-16, Phil Thompson wrote: > On Wed, 16 Sep 2009 20:04:48 +0100, Jeremy Sanders > > wrote: > > Hi - for some reason the following code does not produce the > > correct answer after updating PyQt. > > > > On Ubuntu with the PyQt 4.4.4 package the following returns > > 18.0 > > > > from PyQt4.QtGui import * > > from PyQt4.QtCore import * > > import sys > > > > app = QApplication(sys.argv) > > > > pix = QPixmap(128, 128) > > p = QPainter(pix) > > font = QFont("Times New Roman", 20) > > > > fm = QFontMetricsF(font, p.device()) > > print fm.boundingRect(QChar('0')).height() > > > > On the same system with the same Qt (4.5.0), PyQt-x11- > > gpl-4.6-snapshot-20090906 and returns 32.0! > > > > The text is misaligned when using height to align it using > > the snapshot. > > > > My guess is that the QChar is being promoted to QString. This > > function returns a different result for QString, so it breaks > > my code. The QString version returns the font height, not the > > height of the character given. > > Your guess is correct. > > You could use tightBoundingRect() instead. > > I can back out the automatic conversion from QChar to QString, but that > leaves the question of what should happen with v2 of the QString API, ie. > should QChar not be dropped? I think it would be a pity to keep it. Most of its methods are available in Python anyway, and for those few that aren't couldn't you provide some static methods that either take a one character string or that only consider the first character? -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Selecting several table items
On 2009-08-20, Mads Ipsen wrote: > Hi, > > Ho do I programmatically select several items in a QTableView? I can > select one element by calling the method setCurrentIndex(), but that > only selects a single item. I need to do this in order to write a proper > unit test. > > Best regards, > > Mads Hi Mads, All Q*View widgets have a selectionModel() method that returns a _view_-specific QItemSelectionModel. You can use this to perform complex selections programmatically. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt4 question related to QVariant
On 2009-07-04, Detlev Offenbach wrote: > Hi, > > I would like to store a QModelIndex instance in a QVariant in one > place of my code and retrieve this back out of the variant somewhere > else. > > How do I do that. PyQt4.QtCore.QVariant seems to be missing the > setValue() method. > > Regards, > Detlev If you're going to store anything it ought to be a QPersistentModelIndex. Here's what the QModelIndex docs say "Note: Model indexes should be used immediately and then discarded. ... If you need to keep a model index over time use a QPersistentModelIndex." -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] PyQt4 book - updated examples
Hi, Just to let you know that I've now produced new versions of the PyQt book's examples that work with Python 3---they require PyQt >= 4.5.1. http://www.qtrac.eu/pyqtbook.html (See near the bottom of the page.) They are straight conversions (although done by hand), so they don't take any particular advantage of Python 3's new features, nor or the more Pythonic APIs making their way into PyQt---that'll all have to wait on some future edition, which in turn depends on enough people buying the current edition to convince the publisher that a new edition is worth their while! I've only done the most simple tests on them because I'm so busy with other things at the moment, so let me know if you hit any problems. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt4 for Python 3
On 2009-06-10, Phil Thompson wrote: > On Wed, 10 Jun 2009 07:40:52 +0100, Mark Summerfield wrote: > > On 2009-06-09, Phil Thompson wrote: > >> On Sat, 6 Jun 2009 08:36:44 +0100, Mark Summerfield [snip] > >> I can't reproduce this. Any chance you were hitting the tab order bug > > and > > >> not noticing and the .py file was truncated? > > > > Yes, that is exactly what happened, so presumably the fix will be in the > > next snapshot as per your off-list email. > > Yes (ie. the current snapshot). > > > D'you know when the next actual release will be? I have converted the > > book's examples but don't want to upload them until I can specify a > > version of PyQt for which they'll work (i.e., one that has the tab order > > bug fixed), and that is a proper release rather than just a snapshot. > > I plan new releases of PyQt 3, PyQt 4 and SIP this weekend. PyQt 3 and SIP > have minor regressions (but regressions none the less). Given they need > releases I may as well release PyQt 4 with the tab order fix for Python 3 > as well. Well as soon as there's a PyQt4 for Python 3 I'll post the converted examples---but not before the middle of the month now 'cos I'm too busy next week. > >> > (2) Behaviour change. > >> > QImageReader.supportedImageFormats() and > >> > QImageWriter.supportedImageFormats() both return a list of > >> > QByteArrays. With Python 2 you can convert each QByteArray to a > >> > unicode string like this: > >> > text = unicode(byte_array) > >> > If you change this for Python 3 version to: > >> > text = str(byte_array) # str is Unicode in Python 3 > >> > it will "work", but the string you'll get back will be the repr, > >> > e.g., "PyQt4.QtCore.QByteArray(b'bmp'). > >> > For Python 3 I'm now doing it like this: > >> > text = byte_array.data().decode("ascii") # text == "bmp" > >> > I'm not saying this is the best way, just a way that works. > >> > >> Given that Python 3 wants you to be explicit about encodings then it > >> doesn't seem unreasonable that you have to do this. > >> > >> Happy to debate this as it is the most difficult area of the Python 3 > >> support. > > > > There are very few places in the Qt API where QByteArrays are returned, > > so I don't think it is a problem calling .data().decode("ascii") on them > > or writing a trivial strListFromByteArray() function when they are. I > > only mentioned it so that people are aware of the difference from how it > > is done in Python 2. > > It would have been better if those methods returned a QString. Sure, there are these few unfortunate places in the Qt API that return QByteArrays---the MIME data APIs have the same problem. I think it would be okay (and more convenient) for PyQt to return them as QStrings though since in all the cases I can think of they're always ASCII. > > I found the conversion of the book's examples to Python 3 pretty easy, > > with no nasty surprises or problems, although it was a bit tedious since > > I did them all by hand. > > > > Of course PyQt still has both QString and QVariant---so there is still > > the need for annoying conversions, but at least getting rid of them is > > on the roadmap. > > That is the subject of the next round of development - though 75% of the > work has already been done. I'm really looking forward to that! I think it will be a big step forward. Also, just realised that the roadmap doesn't mention exceptions. I was hoping that, for example, QString.toInt() would return an int on success and raise a ValueError (or whatever) on failure to be more Pythonic. Similarly QFile.open(). The thing I find particularly galling about QString.toInt() returning a tuple is that it is really easy to write: my_int = someQString.toInt() and not realise until sometime later in the code that my_int is in fact a tuple---or maybe not notice at all if you're really only checking for 0: if not my_int: # meant for zero but actually will never get here Still I guess the problem will go away once QString is gone, since we'll just write: my_int = int(some_string) in the normal way. > > PS I think that QUrl is a good candidate for having __hash__. > > The problem is that (unlike the other candidates) QUrl is not > supported by qHash() which means that I'd have to invent a hash > function. This would then cause potential problems if QUrl support was > added
[PyQt] PyQt4 for Python 3
Hi, I've started converting the examples for "Rapid GUI Programming with Python and Qt" to Python 3. I've only hit two problems, one of which I think is a PyQt bug. (1) Bug? Every .ui file converted by pyuic4 gives me an error message like this: $ ./imagechanger.pyw Traceback (most recent call last): File "./imagechanger.pyw", line 264, in fileNew dialog = newimagedlg.NewImageDlg(self) File "/home/mark/books/rapid-gui-programming-with-python-and- qt/eg3/chap06/newimagedlg.py", line 22, in __init__ self.setupUi(self) File "/home/mark/books/rapid-gui-programming-with-python-and- qt/eg3/chap06/ui_newimagedlg.py", line 71, in setupUi self.retranslateUi(NewImageDlg) AttributeError: 'NewImageDlg' object has no attribute 'retranslateUi' In Python 2, pyuic4 adds the retranslateUi() method to the Ui_* class, but this is not happening for Python 3. Python 3.0.1 Qt 4.5.1 PyQt 4.5 on Linux (2) Behaviour change. QImageReader.supportedImageFormats() and QImageWriter.supportedImageFormats() both return a list of QByteArrays. With Python 2 you can convert each QByteArray to a unicode string like this: text = unicode(byte_array) If you change this for Python 3 version to: text = str(byte_array) # str is Unicode in Python 3 it will "work", but the string you'll get back will be the repr, e.g., "PyQt4.QtCore.QByteArray(b'bmp'). For Python 3 I'm now doing it like this: text = byte_array.data().decode("ascii") # text == "bmp" I'm not saying this is the best way, just a way that works. Other than that I found the conversion pretty straightforward. I'll put the Python 3 versions on my website soon, hopefully next week. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Insertrow with QSqlTableModel doesn't work
On 2009-05-22, Volker Helm wrote: > Hi there, > > i've got a problem. In my class enderNewIdOrder(QtGui.QDialog) the > insertRow doesn't work. I did as in "Rapid GUI Programming with Python and > Qt" discribed. But the insert into the Database PostgreSQL over ODBC > doesn't work. Regular changes are applied. > > The application based on QDialog. It has two View (customerView > representing customerModel=QSqlQuery() and projectView representing > projectModel = QSqlTableModel()) > > Here comes my function > > def addProject(self): > customerindex = self.customerView.currentIndex() > if not customerindex.isValid(): > return > QtSql.QSqlDatabase.database().transaction() > record = self.customerModel.record(customerindex.row()) > # getting foreign key > idpartner = record.value(0).toInt()[0] > > # getting new primary key > query = QtSql.QSqlQuery() > query.exec_("SELECT MAX(idproject) FROM project") > if query.next(): > idproject = query.value(0).toInt()[0]+1 > > row = self.projectModel.rowCount() > self.projectModel.insertRow(row) > QtCore.QVariant(QtCore.QDate.currentDate())) > self.projectModel.setData(self.projectModel.index(row, 0), > QtCore.QVariant(idproject)) > self.projectModel.setData(self.projectModel.index(row, 1), > QtCore.QVariant(QtCore.QString(u"New Project"))) > self.projectModel.setData(self.projectModel.index(row, 2), > QtCore.QVariant(1)) self.projectModel.setData(self.projectModel.index(row, > 3), QtCore.QVariant(idpartner)) > self.projectModel.setData(self.projectModel.index(row, 4), > QtCore.QVariant(0)) self.projectModel.setData(self.projectModel.index(row, > 5), QtCore.QVariant(0)) > self.projectModel.setData(self.projectModel.index(row, 6), > QtCore.QVariant(QtCore.QDateTime.currentDateTime())) > > QtSql.QSqlDatabase.database().commit() At this point you could try doing this (untested): self.projectModel.submitAll() > index = self.projectModel.index(row, 1) > self.projectView.setCurrentIndex(index) > self.projectView.edit(index) > > > I hope anybody ould give me a hint, what I'm doing wrong. It cost me the > last 10 hours. If I insert the row manualy by inserting folling code > between the transaction. I get the new Line, but I can edit the content > only after I left the current customer and reread the actual customer. > > Here the manual insert > > query.prepare("INSERT INTO project (idproject,description ,idunit, > idpartner,idaddress, statusid,created ) " "VALUES (:idproject, > :description,:idunit,:idpartner,null,0, now())") > query.bindValue(":idproject", QtCore.QVariant(idproject)) > query.bindValue(":description", > QtCore.QVariant(QtCore.QVariant(QtCore.QString("Neues Projekt" > query.bindValue(":idunit", QtCore.QVariant(1)) > query.bindValue(":idpartner", QtCore.QVariant(idpartner)) > query.exec_() > > Thanks in advance, > > Volker -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] doubts about Example Book Rapid GUI Programming with Python and Qt
On 2009-05-04, Airton Arantes wrote: > Hello Folks, I'm beginning using PyQt through the book Rapid "GUI > Programming with Python and Qt". > > I'm seeing a strange statement at chapter 4(page 129). > > while QTime.currentTime() < due: > time.sleep(20) # 20 seconds > > > Where I must to put this statement above? I did this so far: > > http://pastebin.com/m645e6291 All the book's examples are available online so you can download them and see them complete and in context: http://www.qtrac.eu/pyqtbook.html -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QTableView header connection
On 2009-03-18, Till Gerken wrote: > On Wed, Mar 18, 2009 at 3:40 PM, Gert-Jan wrote: > > Class GUI: > >def __init__(self): > >tableWidget = QtGui.QTableWidget() > ># Code to insert 5 columns and make a horizontal header) > >self.connect(tableWidget.horizontalHeader, > > QtCore.SIGNAL("clicked()"), self.random_function) > > > >def random_function(self): > >print 'ok' > > > > However, double-clicking the header does not make the console print 'ok'. Uh, just off the top of my head (and untested), shouldn't it be: self.connect(tableWidget.horizontalHeader(), QtCore.SIGNAL("clicked(QModelIndex)"), self.random_function) or QtCore.SIGNAL("doubleClicked(QModelIndex)") or if you just want to know the column that was clicked QtCore.SIGNAL("sectionClicked(int)") > > If you double click, the signal should be doubleClicked(). > > Till > > _______ > PyQt mailing listPyQt@riverbankcomputing.com > http://www.riverbankcomputing.com/mailman/listinfo/pyqt -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QSortFilterProxyModel.createIndex from within a slot callback
On 2009-02-27, Zorg 421 wrote: > Hello PyQt users, I do not know how to use the third argument of > createIndex in the following code. I didn't have time to look at your code, but the third argument must be a QModelIndex, specifically the model index of the relevant item's _parent_. For top-level items this is easy: QModelIndex(); but inside the method using index.parent() should work fine. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Catching key events Re: [PyQt] Catching key events
On 2009-01-19, Frédéric wrote: > Le 19/1/2009, "Mark Summerfield" a écrit: > >I suspect that using grabKeyboard()/releaseKeyboard() is not the right > >approach---for example, I've never seen them used in practice and have > >never used them myself. > > > >PyQt has an event handling hierarchy, and IMO it is best to start with > >the least powerful approach and work up 'til you get what you need. > > > >So if you want to catch particular keys you could create a QShortcut for > >each key sequence in the main window's __init__ and connect each > >shortcut to a method. > > > >If that isn't sufficient, then you could try reimplementing > >keyPressEvent()---and to propagate key event you don't want to handle > >yourself just call the base class version with the arguments you > >received. (And of course see David's reply.) > > > >If you want more control than that you could reimplement event(), or you > >could add one or more eventFilters() (but never use many of them since > >they can hurt performance). And that's not quite all. Keep in mind that > >PyQt is _different_ from Gtk so IMO it is best to find the PyQt-ish > >approach rather than to attempt a straight conversion from Gtk to PyQt > >code. > > I totally agree that mimic PyGTK is not very efficient. In fact, I'm > porting my app to Qt this way to quickly have something running, and > test all other problems (packaging, and so). Then, I plan to redesign > it, and use all Qt great features. > > Even if using grabKeyboard()/releaseKeyboard() in a few points works > really great, exactly how I want, I will try QShortcut... > > About keyPressEvent, I'm using it, and it works (thanks to David), > except that the repeat sends press followed by release events, and I > really need to only get the press event when the key is pressed, and the > release one when it is released. I didn't find yet a way to do that. At > which level this feature is implemented, so I can try to change it? > Should I go down to the event() callback? I'd stick to reimplementing keyPressEvent. The QKeyEvent parameter can tell you if the press is due to autorepeat or a genuine new keyclick. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Catching key events
On 2009-01-17, Frédéric wrote: > On vendredi 16 janvier 2009, Frédéric wrote: > > 1) catching key events > > > > I found that I have to implement the keyPressEvent() method. I did this > > in the mainWindow, but the behaviour depend where is the focus. And as I > > want to catch arrow keys, it also change the focus! What is the proper > > way to do this? I also want to rebind key TAB, to avoid changing the > > focus, space, and enter... > > Ok, I solved most of my problems using grabKeyboard()/releaseKeyboard() > methods. > > I still have an issue: when I hold down a key, once the repeat starts, I > receive both KeyPressed and KeyReleased events. This is a different > behaviour as PyGTK, where I only received the key-pressed-event while > holding it down, and the key-release-event when I release the key. > > Is there a way to do this in PyQt? I want to start the motor head when I > press the key, and stop it when I release the key. Now, it does not work, > as the motor is started/stopped too quickly (which is not very good)... Frédéric, I suspect that using grabKeyboard()/releaseKeyboard() is not the right approach---for example, I've never seen them used in practice and have never used them myself. PyQt has an event handling hierarchy, and IMO it is best to start with the least powerful approach and work up 'til you get what you need. So if you want to catch particular keys you could create a QShortcut for each key sequence in the main window's __init__ and connect each shortcut to a method. If that isn't sufficient, then you could try reimplementing keyPressEvent()---and to propagate key event you don't want to handle yourself just call the base class version with the arguments you received. (And of course see David's reply.) If you want more control than that you could reimplement event(), or you could add one or more eventFilters() (but never use many of them since they can hurt performance). And that's not quite all. Keep in mind that PyQt is _different_ from Gtk so IMO it is best to find the PyQt-ish approach rather than to attempt a straight conversion from Gtk to PyQt code. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Log viewer
On 2009-01-16, Frédéric wrote: > On vendredi 16 janvier 2009, Mark Summerfield wrote: > > If you have 100K + log lines then a list model + QListView (+ custom > > delegate if you want fine control over rendering); but anything less and > > QPlainTextEdit + a simple data class should be fine. (I'm guessing about > > the 100K of course but you get the point.) > > I like this QListView idea :o) This will allow a better control on the > display, like dynamically hide/show specific levels or so. Good:-) > I read your paper about the MVC improvement over Qt default delegate > implementation; do you explain it in your python/Qt book (I'm about to > receive it), with python examples? If you mean my document on generic delegates, yes, I cover that in the PyQt book in chapter 16. > I enjoy very much such patterns, and I will certainly comme back to > you (through the list) for more advices (I'm looking for a generic > plugins framework)... > > Thank you again for you help. :-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Log viewer Re: [PyQt] Log viewer
On 2009-01-16, Frédéric wrote: > Le 16/1/2009, "Mark Summerfield" a écrit: > >QPlainTextEdit is optimized for use as a log display and has > >appendHtml() and appendPlainText(). For Qt 4.3 or earlier use QTextEdit > >or QTextBrowser instead. > > Thanks, Mark. So, you suggest I subclass QPlainTextEdit to add the > write() and flush() method (the logging handler mandatory interface), > and give that widget to the logger? Then, it won't have any parent, as > the dialog where I show the log is created on user request (and > destroyed as soon as the user close it)... Will it be possible to > reparent it on the fly in this dialog? I thought you meant logging in the GUI rather than the Python standard library's logging module. I would write a pure data class and only use QPlainTextEdit to display the data when neeeded. > Is there a way to have something more model/view oriented? Some sort of > non-graphical object, the buffer (model), I can attached later to the > QPlainTextEdit (view)? You can kind of do it using a QTextDocument, but unless the demands are huge using a data class and feeding a QPlainTextEdit should work okay. (And if not you could always create a list model and create a use a QListView.) > I would also like to be able to change the attributes (color, font...) of > each log entry, according to its level. This can be easily done in html, > but then, it will be harder, later, to get back the raw text (the user > can save the log from the log dialog). Is there any solution, here? Well if you held the data in a separate class (or a custom model) you could keep it as plain text but provide methods that output html for clients that want it. If you have 100K + log lines then a list model + QListView (+ custom delegate if you want fine control over rendering); but anything less and QPlainTextEdit + a simple data class should be fine. (I'm guessing about the 100K of course but you get the point.) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Log viewer
On 2009-01-16, Frédéric wrote: > I'm using the python logging module to log everything. I would like to > make a log viewer in my Qt application. This viewer can be opened from a > menu, and is modal. > > I already did such viewer in gtk, using a textView/textBuffer. I created > a class from textBuffer, and I added write() and flush() method, so I > can give this object to the logging module as a handler. Then, when I > want to display the logs, I just create the textView, set its internal > buffer to the one I gave to logging, and so the logs appear. > > I would like to do the same in Qt, but I don't know how. I found a > QTextDocument class, which sems to be the same as gtk textBuffer, but it > does not have a appendText or appendHtml methods, nor a way to limit the > number of entries. > > Any idea how I can do that? QPlainTextEdit is optimized for use as a log display and has appendHtml() and appendPlainText(). For Qt 4.3 or earlier use QTextEdit or QTextBrowser instead. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QPainter bug(?) in printing.pyw example from PyQt book
On 2009-01-08, Denis Konchekov wrote: > System: Ubuntu 8.10, Python 2.5.2, PyQt 4.4.3 > Book "Rapid GUI Programming with Python and Qt", example from chap13 > Faded cells in first table after printing to pdf (before changing pen > color). > See screenshot in attachment or here: > http://img404.imageshack.us/done.php?l=img404/1899/75073848lv9.jpg > Everything ok after adding yet another painter.setPen(Qt.color): > > <...> > y += serifLineHeight > if balance < 0: > painter.setPen(Qt.red) > text = "Please remit the amount owing immediately." > else: > text = ("We are delighted to have done business " > "with you.") > painter.drawText(x, y, text) > painter.setPen(Qt.red) #added > painter.setPen(Qt.black) > y += int(serifLineHeight * 1.5) > painter.drawText(x, y, "Transactions:") > y += serifLineHeight > option = QTextOption(Qt.AlignRight|Qt.AlignVCenter) > for date, amount in statement.transactions: > <...> > > mysticism? Hi Denis, I get exactly the same problem as you do with Qt 4.4, so it looks to me like a Qt (or PyQt) bug that was not present in Qt 4.3. My preferred workaround is: painter.setPen(Qt.NoPen)# workaround painter.setPen(Qt.black) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Learning path
On 2009-01-09, Steven Woody wrote: > Hi, > > I want to use PyQt but I don't get experience with Qt itself. What's > the best learning path to me? Any suggestion will be highly > appreciated! Well obviously the first step is to buy my book:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187' ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt4.Qtcore defines 'hex'
On 2009-01-07, Chris Withers wrote: > Phil Thompson wrote: > >>> This has been discussed thousands of times and it starts getting > >>> annoying. > >> > >> Yes, it is annoying that all the example code continues to be in a form > >> that confuses users trying to learn PyQt. > > > > *None* of the PyQt4 examples uses star imports. > > Hmmm, apologies then, must have been exclusively a problem with Mark > Summerfield's tutorial stuff. I have now switched to a new style for imports, for example: from PyQt4.QtCore import (PYQT_VERSION_STR, QFile, QFileInfo, QSettings, QString, QT_VERSION_STR, QTimer, QVariant, Qt, SIGNAL) from PyQt4.QtGui import (QAction, QActionGroup, QApplication, QDockWidget, QFileDialog, QFrame, QIcon, QImage, QImageReader, QImageWriter, QInputDialog, QKeySequence, QLabel, QListWidget, QMainWindow, QMessageBox, QPainter, QPixmap, QPrintDialog, QPrinter, QSpinBox) This avoids importing confusing junk while still allowing you to write nice things like: action = QAction("Action") The disadvantage is that you keep having to extend the lists of imports as you develop and maintain your code. I don't want to change this for the book's examples because I want them to exactly match the text---although actually, the only change is to the imports, the use of the classes is unchanged. However I've done a separate set of Python 2.6 versions of the examples and these use the new import style. > FWIW, I still think sticking a _ on the end of the name is silly... Yes, but it has precedents in PyQt already, e.g. QApplication.exec_(). > > (and in my previous mail when I said "David" I actually meant "Mark", > happy new year ;-) ) Understandable since David is a much more regular poster than I am:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] OT: New Book: Programming in Python 3
Hi, I hope you'll excuse this slightly off-topic announcement, but now that Python 3 final has been released, I guess sometime soon (next year?) many of us hope to be using PyQt for Python 3, and so might be interested in learning Python 3 in advance... I've just finished writing a new book: "Programming in Python 3: A Complete Introduction to the Python Language" ISBN 0137129297 http://www.qtrac.eu/py3book.html I've been working on this for more than a year, testing the examples against every Python 3 alpha and beta, and against the final release (using Python's unit test and doctest modules of course:). The book has just gone into production and should be available in print at the end of this month in the U.S., and a month or two later elsewhere. The book's web page has links to a draft of the introduction and to safari books online where you can read extracts. The book is aimed at a wide audience, but assumes some programming experience (not necessarily Python, not necessarily object-oriented). It teaches solid procedural style programming, then builds on that to teach solid object-oriented programming, and then goes on to more advanced topics (e.g., including a nice way to create validated attributes by combining class decorators with descriptors). But even newcomers to Python 3 should be able to write useful (although small and basic) programs after reading chapter 1, and then go on to create larger and more sophisticated programs as they work through the chapters. Note: The only GUI coverage is of tkinter! (But still worth reading just to see what a pure joy PyQt is by comparison;-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Re: dialogs and extentions
On 2008-10-29, Wim Verhavert wrote: > Thanks for your reply Mark. I tried the discussed procedure this > afternoon, and yes this works, but as you said, this will not allow > for user resize, which is a pitty. The older approach did allow for > resize, so I consider this a step back. Do you see any reason why they > want to remove this from the API? I don't know why they made that change. If you don't call setSizeConstraint() the dialog is resizable and is the right size when you start and the right size when the extension is shown. But when the extension is hidden again the dialog does not resize down, so that's the only case you have to fix---but I don't think it is easy to do! > Thanks again, and by the way: your book is great! Thanks:-D > Wim > > On Wed, Oct 29, 2008 at 4:02 PM, Mark Summerfield <[EMAIL PROTECTED]> wrote: > > On 2008-10-29, Wim Verhavert wrote: > >> I already found out that you can set the orientation with a call to > >> 'setOrientation(Qt.Vertical)'. That solves my problem for now. But > >> while I was searching for a solution I found the following: > >> http://doc.trolltech.com/4.4/qdialog-obsolete.html. There they state > >> that my solution is obsolete and "we strongly advise against using > >> them in new code". But the new method they propose, i.e. simply hide > >> or show the widgets, will not resize my dialog properly (it will only > >> grow and not shrink). I played around with this for a while but > >> couldn't get it to working. Has anybody done it using this new method. > >> Does it shrink properly again? How do you do it? > > > > A technique for doing what you want is to: > > (1) Put all the widgets that belong in the extension inside a QFrame > >that is itself laid out as usual > > (2) In the form's __init__ > >(a) hide the frame (thus hiding all the widgets it contains) > >(b) call: self.layout().setSizeConstraint(QLayout.SetFixedSize) > >(c) connect the button widget you're using to hide/show the > >extension's toggled(bool) signal to the frame's setVisible(bool) > >slot. > > > > Using this approach the dialog shrinks or grows as appropriate. The only > > downside is that it is not user resizeable. > > > > An example is in my book "Rapid GUI Programming with Python and Qt", and > > you can download the examples from here: > > http://www.qtrac.eu/pyqtbook.html > > > > The example is: > >eg/chap09/findandreplace.{py,pyw} > > (the .pyw version is all in code the .py version's form is a .ui file) > > > > > > -- > > Mark Summerfield, Qtrac Ltd, www.qtrac.eu > >C++, Python, Qt, PyQt - training and consultancy > >"C++ GUI Programming with Qt 4" - ISBN 0132354160 -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Re: dialogs and extentions
On 2008-10-29, Wim Verhavert wrote: > I already found out that you can set the orientation with a call to > 'setOrientation(Qt.Vertical)'. That solves my problem for now. But > while I was searching for a solution I found the following: > http://doc.trolltech.com/4.4/qdialog-obsolete.html. There they state > that my solution is obsolete and "we strongly advise against using > them in new code". But the new method they propose, i.e. simply hide > or show the widgets, will not resize my dialog properly (it will only > grow and not shrink). I played around with this for a while but > couldn't get it to working. Has anybody done it using this new method. > Does it shrink properly again? How do you do it? A technique for doing what you want is to: (1) Put all the widgets that belong in the extension inside a QFrame that is itself laid out as usual (2) In the form's __init__ (a) hide the frame (thus hiding all the widgets it contains) (b) call: self.layout().setSizeConstraint(QLayout.SetFixedSize) (c) connect the button widget you're using to hide/show the extension's toggled(bool) signal to the frame's setVisible(bool) slot. Using this approach the dialog shrinks or grows as appropriate. The only downside is that it is not user resizeable. An example is in my book "Rapid GUI Programming with Python and Qt", and you can download the examples from here: http://www.qtrac.eu/pyqtbook.html The example is: eg/chap09/findandreplace.{py,pyw} (the .pyw version is all in code the .py version's form is a .ui file) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt menu and tool tip font
On 2008-10-24, Thorsten Kampe wrote: > Hi, > > not sure whether this is really a PyQt thing but I'll ask anyway: > > PyQt applications (like Sandbox[1]) on Linux have a horrible looking and > much too small font for the menus, tool tips and for the status bar - > while on Windows it looks totally normal (like all other applications). > > Where or how can I configure the font and the font size for the menus, > the tool tips and the status bar?! I have encountered this problem in the past, but not in recent years with modern Linux distros. In theory Qt GUI applications accept a -font command line option that QApplication takes care of. The docs say that this must be in XLFD format, e.g., ./prog.pyw -font -*-sans\ serif-*-r-*-*-16-*-*-*-*-*-*-* This approach has the advantage that you don't need access to the source. When you create a QApplication object it object "inherits" the user's preferences for fonts, colours, etc. And all the application's top-level widgets inherit those properties from QApplication, and all the child widgets inherit those properties from their parents. So if you set the font in QApplication, it will affect the whole app. (In the case of Sandbox.pyw, it will only affect menus and toolbars and similar, since the program allows the user to override the fonts used for showing code.) So you could go to wherever the QApplication instance is created, and on the next line change the font, e.g. app = QApplication(sys.argv) app.setFont(QFont("Helvetica", 16)) You can find out what fonts are availabe to Qt using QtGui.QFontDatabase(). -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] 2 litlle questions
On 2008-10-23, kib2 wrote: > Hi, > > I'm having troubles in retrieving a QTextEdit selection. > I join a little test app (main.py). Launch it, select all the text in the > area then press F1, the quit. > The output is really strange. In fact I need to split the retrieved lines, > but the returned line separators are unknow chars for my computer. You're getting the Unicode line break character. Add this line before you print the text: sel = sel.replace(u"\u2029", "\n") > Another : I saw that Mark Summerfield recently played with the Poppler > bindings for Qt4. Is there any port of it for PyQt ? I know there's one > link on the Wiki, but there's not even a single word on the version and how > to compile it under a Windows machine. You could always create your own PyQt bindings using sip:-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QSpinBox with hex format
On 2008-10-23, Nahuel Defossé wrote: > Hi > I'd be glad to receive any hint about how to subclass QSpinBox in order to > use hex format. > Thanks > Nahuel There's an example of subclassing a QSpinBox for roman numerals in my PyQt book: http://www.qtrac.eu/pyqtbook.html You can download the examples, it is chap11/romanspinbox.py There's an example of subclassing a QSpinBox for hex numbers in my C++/Qt book (so it is in C++ but easy to translate to PyQt): http://www.informit.com/store/product.aspx?isbn=0132354160 Again, you can download the examples, it is in chap05/hexspinbox -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] strange dialog slowness
Hi, I've encountered an odd behaviour in PyQt4 which seems to be peculiar to my Fedora 8 system. I have PyQt 4.4.2, Qt 4.4.0, and Python 2.5.1 installed from packages and they work fine. I also have PyQt 4.4.3, Qt 4.4.3 and Python 2.5.2 installed locally on both my Fedora 8 system and on my Kubuntu system. On the Kubuntu system everything is fine, but on Fedora 8, windows take a long time to appear for the first time---for example, the file open dialog takes around 14 seconds even when the current directory doesn't have many items. I tried building everything from scratch, I tried both later and earlier versions, and I still have the same problem. The slowness does not affect the locally installed Qt for C++/Qt programs, only for PyQt. Phil hasn't encountered this problem and suggested using debug versions of the Qt libraries to try to trace it; but first I wondered if anyone else had hit the problem and maybe had a fix they could suggest? Thanks! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QSqlTableModel and complex queries
On 2008-10-08, Aaron Digulla wrote: > Scott Frankel schrieb: > > This seems beyond the scope of > > QSqlRelationalTableModel. > > During my work on UPCScan, I've found that the QSqlRelationalTableModel > and the related table view are too buggy and too limited to be useful. > In the end, I've ripped all the code out again and wrote my own > implementation. Problems that I've encountered: > > - When you change anything in the model, the view resets itself. You > lose the current selection and the current scroll position. That is intended behaviour. Reset is the model's way of telling its associated views that some major data change has occurred and that all data shown must be refetched. So if you want to keep selection and position info you must handle that yourself. If you've just changed a one or a few items then emit the dataChanged() signal with the relevant QModelIndexes; that shouldn't affect seletions etc. and the views will just refetch what has changed. > - You can't tell the model that you've just added a row to the table. That's handled in your QAbstractTableModel subclass's insertRows() reimplementation, where you call beginInsertRows(), then insert your row or rows, then call endInsertRows(). > - I have a column with binary data. There is no way to inject a mapper > to turn this into something useful for the UI. > > - I couldn't update the binary data with in setData(). You'd need to implement a custom delegate. A custom delegate you control over how data is displayed or over how it is edited or both. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Extracting QSqlQuery results in PyQt4
On 2008-10-08, mir amicitas wrote: > I am trying to use SQLite in a PyQt4 application. I am running into a > problem where it is taking a really long time to get the data out of > the QSqlQuery object after a query is completed. Here is a code > snippet with the relevant parts: > > # > self.selected_columns = self.table_definition['track'] > select_string = ','.join(self.selected_columns) > > query_str = 'SELECT %s FROM track %s'%(select_string, where_string) > > start_time = time.clock() > self.query.prepare(query_str) > self.query.exec_() > util.message('Query took:', time.clock() - start_time, 'seconds') > > print '' > print query_str > > results = [] > header = self.selected_columns > > self.query.first() > > while self.query.isValid(): > record = [self.query.value(index).toString() for index in > range(len(header))] > results.append(record) > self.query.next() > > util.message('Selected', len(results), 'records.') > > util.message('Unpacking Took:', time.clock() - start_time, > 'seconds') I think someone has already given some suggestions regarding speed, so here is one on style: Instead of calling query.first() and query.isValid() just do: while query.next(): ... The first time query.next() is called it will go to the first record; and when there are no more records it will return False. [snip] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Re: PyQt4 and Python 3.0
On 2008-10-06, Giovanni Bajo wrote: [snip] > "PyQt5" seems confusing to me when/if Qt5 comes out (and I always find > confusing that PyQt4 version number is too similar to Qt version number; > I'd go for something totally different like "PyQt4 version 18"). I also think PyQt5 would be confusing; and agree with Giovanni that a completely different numbering scheme for PyQt would be better. At first I used to think that say, PyQt 4.2 meant you needed Qt 4.2, when in fact you can use earlier Qt 4's with it. Something like PyQt4-25 or PyQt4/25 suggests to me "version 25 of PyQt4 for Qt 4.x" Or maybe something more explicit: PyQt25/Qt4? -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt4 and Python 3.0
On 2008-10-03, Paul A. Giannaros wrote: > On Fri, Oct 3, 2008 at 5:08 PM, Mark Summerfield <[EMAIL PROTECTED]> wrote: > > On 2008-10-03, Phil Thompson wrote: > >> On Fri, 3 Oct 2008 17:11:19 +0200, Detlev Offenbach > > > > Here's my personal "wish list" for Python 3/PyQt4 (including those that > > Phil is going to do as he says above): > > > > - No QString, only str, plus some static functions for things that str > > doesn't provide, e.g., QString.simplified(s : str) -> str > > - No QByteArray, only bytes (or bytearray) > > - No QVariant, only object > > - Guarantee that "from PyQt4.QtGui import *" and similar will only > > import objects whose name begins with capital Q. > > That'd be cool. An alternative that I think would be even better > would be to provide a "Qt" namespace as per QtRuby and drop the > Q prefix from the classes, so Qt.Application, Qt.Widget, &c. > That'd dodge the ugly namespace pollution while not causing > much more typing. I like that:-) But how do we then distinguish QtGui.QApplication from QtCore.QApplication? (Or does that even matter?) But I'm not keen on pyqt4 and other lowercase names as Daniel suggested. IMO lowercase is for Python's standard packages; I think mixed cased is best for own and third party to help avoid clashes. -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] PyQt4 and Python 3.0
On 2008-10-03, Phil Thompson wrote: > On Fri, 3 Oct 2008 17:11:19 +0200, Detlev Offenbach > > <[EMAIL PROTECTED]> wrote: > > Hi, > > > > will there be PyQt4 support for Python 3.0 once it goes final? > > Not straight away. I will take the opportunity to break backwards > compatibility (eg. removing QVariant, QString, QChar, QByteArray etc), > and those changes will be made over a period of time. So it may be a > while before the API is stable enough for anything other than playing. I've been waiting for someone to mention this... Here's my personal "wish list" for Python 3/PyQt4 (including those that Phil is going to do as he says above): - No QString, only str, plus some static functions for things that str doesn't provide, e.g., QString.simplified(s : str) -> str - No QByteArray, only bytes (or bytearray) - No QVariant, only object - Guarantee that "from PyQt4.QtGui import *" and similar will only import objects whose name begins with capital Q. - Make PyQt more Pythonic. So use exceptions not error codes, for example, make QFile.open() raise an exception on error. Also, provide QDataStream.readColor(), QDataStream.readHostAddress(), etc., i.e., a reader and a writer _method_ for every QDataStream type for those allergic to << and >>. - Support Qt collection types that don't have Python equivalents, e.g., QMap (with bytes keys and values) and QVector (with bytes items), plus wrappers so that strs can be used (just like the bsdb module offers). - Support super() so that it can be used in PyQt subclasses just like any other subclasses. ;-) -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] Rapid PyQt book - examples for Python 2.6
Hi, Just to let you know that I've now produced an additional version of the examples that accompany my book, "Rapid GUI Programming with Python and Qt", ISBN 0132354187. The new archive uses Python 2.6 syntax and is available from http://www.qtrac.eu/pyqtbook.html I've also taken the opportunity to change the import style from the space-saving one used in the book (from PyQt4.QtGui import *) to the one most commonly used in practice (from PyQt4 import QtGui). The new import style and the use of the print() function and the str.format() method are the main syntactic changes. Since Python 2.6 isn't officially available yet I've tested against release candidate 2 and the PyQt 4.4.4 snapshot and used the -3 flag. I hope that this is useful to those who want to make the move to 2.6! -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297' ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Strange shadowing of hex() function by PyQt4.QtCore
On 2008-08-08, Phil Thompson wrote: > On Fri, 8 Aug 2008 08:02:55 +0100, Mark Summerfield <[EMAIL PROTECTED]> wrote: > > On 2008-08-08, Boris Barbour wrote: > >> Hi, > >> > >> Importing PyQt4.QtCore seems to alter or shadow the builtin hex() > >> function. I'm afraid I haven't tracked things down further - I just > >> learnt the hard way to "import" instead of "from import *". However, > >> I'm not sure the clash is intended, so I'm reporting it. > >> > >> Best regards, > >> > >> Boris > > > > [snip] > > > > It is unfortunate that doing * imports on PyQt4 brings in some objects > > which don't begin with q or Q. Here's a solution for hex shown as an > > > > IDLE session: > > >>> hex(123) > > > > '0x7b' > > > > >>> from PyQt4.QtCore import * > > >>> hex(123) > > > > Traceback (most recent call last): > > File "", line 1, in > > hex(123) > > TypeError: argument 1 of hex() has an invalid type > > > > >>> __builtins__.hex(123) > > > > '0x7b' > > > > >>> # restore built-in hex > > >>> hex = __builtins__.hex > > >>> hex(123) > > > > '0x7b' > > > > In Python 3 you'll be able to do "import builtins" and use > > builtins.hex(). But I'm hoping that in PyQt4 for Python 3, the * imports > > will only import objects that begin with q or Q, forcing the handful of > > objects that don't meet this criterion to either be imported explicitly > > or accessed fully qualified. [Any comment on this, Phil?] > > I'm not going to treat specific names differently as it's not a PyQt > problem. > > Don't use "import *" - ever, in any Python code. Even for < 1000 line utilities or for interactive experimentation? Anyway, I still think you should define __all__ to only include objects that match ^[Qq]\w+$ -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "C++ GUI Programming with Qt 4" - ISBN 0132354160 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Strange shadowing of hex() function by PyQt4.QtCore
On 2008-08-08, Boris Barbour wrote: > Hi, > > Importing PyQt4.QtCore seems to alter or shadow the builtin hex() > function. I'm afraid I haven't tracked things down further - I just > learnt the hard way to "import" instead of "from import *". However, > I'm not sure the clash is intended, so I'm reporting it. > > Best regards, > > Boris [snip] It is unfortunate that doing * imports on PyQt4 brings in some objects which don't begin with q or Q. Here's a solution for hex shown as an IDLE session: >>> hex(123) '0x7b' >>> from PyQt4.QtCore import * >>> hex(123) Traceback (most recent call last): File "", line 1, in hex(123) TypeError: argument 1 of hex() has an invalid type >>> __builtins__.hex(123) '0x7b' >>> # restore built-in hex >>> hex = __builtins__.hex >>> hex(123) '0x7b' In Python 3 you'll be able to do "import builtins" and use builtins.hex(). But I'm hoping that in PyQt4 for Python 3, the * imports will only import objects that begin with q or Q, forcing the handful of objects that don't meet this criterion to either be imported explicitly or accessed fully qualified. [Any comment on this, Phil?] -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Rapid GUI Programming with Python and Qt" - ISBN 0132354187 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] [pyconuk] PyQt4 Tutorial
Hi, To quote Michael Foord: "PyCon UK starts with a tutorial day, when you have the opportunity to attend two half day tutorials for only £30." One half day tutorial on the Friday will be "Practical Python GUI Programming with PyQt4", summarised here: http://pyconuk.org/talk_abstracts.html#1033 It is aimed at Python 2 programmers, although no GUI experience is assumed. You will need a laptop---Windows/Mac/Linux---whatever you have, with Python 2.5 and PyQt4 and an editor (e.g. IDLE) _already installed_, since the tutorial is a mixture of exposition and hands on programming. [It may be possible to borrow a suitable laptop---please contact the organisers about this.] For those just wanting an introduction to GUI programming with PyQt4, there will be a one hour talk on Saturday, summarised here: http://pyconuk.org/talk_abstracts.html#1032 Conference web site: http://pyconuk.org -- Mark Summerfield, Qtrac Ltd, www.qtrac.eu C++, Python, Qt, PyQt - training and consultancy "Programming in Python 3" - ISBN 0137129297 ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Comparing QString with QChar
On 2008-06-27, Phil Thompson wrote: > On Fri, 27 Jun 2008 09:38:04 +0100, Mark Summerfield <[EMAIL PROTECTED]> > wrote: > > Hi, > > > > I got caught by this today: > > >>> from PyQt4.QtCore import * > > >>> s = QString("X") > > >>> c = QChar("X") > > >>> s[0] == c > > > > False > > > > >>> s[0] == QString(c) > > > > True > > > > In C++/Qt if you do the s[0] == c comparison it will return true because > > operator[] returns a const QChar &, but in PyQt4 s[0] is still a > > QString---which makes sense because in Python a char is just a str of > > length 1, but maybe this particular case could be handled more > > intuitively? > > By allowing a QChar whenever a QString is expected? Seems reasonable given that Python doesn't make the char/str distinction. Of course what would be really nice is to say something like: from __future__ import native_str to help get rid of QString usage. (I _like_ QString, but I just find the Qt Jambi solution so much better;-) -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] Comparing QString with QChar
On 2008-06-27, Hans-Peter Jansen wrote: > Am Freitag, 27. Juni 2008 schrieb Mark Summerfield: > > Hi, > > > > I got caught by this today: > > >>> from PyQt4.QtCore import * > > >>> s = QString("X") > > >>> c = QChar("X") > > >>> s[0] == c > > > > False > > > > >>> s[0] == QString(c) > > > > True > > > > In C++/Qt if you do the s[0] == c comparison it will return true because > > operator[] returns a const QChar &, but in PyQt4 s[0] is still a > > QString---which makes sense because in Python a char is just a str of > > length 1, but maybe this particular case could be handled more > > intuitively? > > Mark, while I won't anticipate Phil's statement, the problem is: PyQt > is unfortunately full of those unintuitivnesses, because C++ implicit > casts are hard to handle here. > > If you start formulate the rules, for which you want to do automatic > conversions, you will find yourself in a twisted maze quickly. Doing > them one by one (as this case might imply) is an awful lot of work.. > > The question is - where to start, where to stop? I think that strings are the most important because they are used in all contexts by all applications... but hopefully QString (and QVariant) will disappear in the Python 3 version of PyQt where we'll just enjoy str and object, plus a few static methods like QString.simplified(s:str)->str :-) -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
[PyQt] Comparing QString with QChar
Hi, I got caught by this today: >>> from PyQt4.QtCore import * >>> s = QString("X") >>> c = QChar("X") >>> s[0] == c False >>> s[0] == QString(c) True In C++/Qt if you do the s[0] == c comparison it will return true because operator[] returns a const QChar &, but in PyQt4 s[0] is still a QString---which makes sense because in Python a char is just a str of length 1, but maybe this particular case could be handled more intuitively? -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QVariant and Python list
On 2008-05-30, Phil Thompson wrote: > On Wednesday 28 May 2008 6:35:32 pm Laurent Léonard wrote: > > Hi, > > > > I read QList and QMap are not implemented in PyQt, because of the > > presence of Python lists and dictionaries. > > > > But how can I use QVariant to "encapsulate" Python lists and dictionaries > > ? When I try to do it I get the following error message : "TypeError: > > argument 1 of QVariant() has an invalid type" > > I'd be surprised if you got that error with the current version. > > There are a number of issues here which I'd like feedback on... > > The various QVariant ctors allow type convertors to have an effect, ie. in > SIP terms they don't have the /Constrained/ annotation. For example, > QVariant(const QStringList &) will accept a Python list of strings. I think > this is a mistake as QVariant([]) will be treated as an empty QStringList > but QVariant([0]) will be treated as a Python object. > > So I think every QVariant ctor that takes a Qt class should have > /Constrained/ applied. > > However that would then mean that QVariant([]) would now be treated as an > empty QList and still not as a Python object. > > For similar reasons QVariant({"abc": 0}) would be treated as a QMap, but > QVariant({1: 0}) would be treated as a Python object. > > Therefore I also want to drop support for QVariant(QList<>) and > QVariant(QMap<>) completely. > > The advantage is that anything that is not a fundamental type (int, float > etc) or a wrapped type will be treated as a Python object and can be > retrieved using toPyObject() - all very consistent. > > The disadvantages are that it is an incompatible change. It also becomes > impossible to create a QVariant(QList<>) or QVariant(QMap<>) from Python > (although I can't find a use case in Qt). I could add fromQVariantList() > and fromQVariantMap() methods to get round the second problem. I have a rather more controversial suggestion (so maybe for Python 3/PyQt). Why not kill QVariant and QStringList and QString altogether! Trolltech did just that with Jambi (Java/Qt), for which they use the native Java Object and Java String, etc. No matter how carefully PyQt honours the buffer API you still hit nasty problems from time to time. For example, if you use the gzip module with a QString filename you get a corrupt file; but it works perfectly with a unicode or str filename. But the point is that if PyQt only used unicode (str in Python 3) and bytes (for QByteArray) and object (for QVariant), none of those kind of subtle problems would arise. It would also put an end to having to know which kind of string you have and converting between the two kinds. Of course QString has some methods that unicode/str doesn't have. That was also true of Java String and Trolltech solved that by providing some static methods (that accept and return Java Strings) to fill the gaps; the same could be done in PyQt. My 2c;-) -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] QWidget focusInEvent() ?
On 2008-05-29, B Clowers wrote: > I have what would seem to be a fairly small problem. My > application has a main window that currently has the ability to spawn > a number of Non-Modal QWidgets in their own respective windows. > I need to emit or catch a signal that is produced whenever a > particular QWidget in its own window gets the focus. After > looking at the documentation I can't seem to find a particular signal > that is emitted. Does anyone have an idea how to accomplish this > task? It isn't quite so simple because focus is not a high level abstract behaviour which signals and slots are for, but a low level detail. So I think you'll have to use the event handling mechanism. Here's something that works for me on Linux, i.e., if I run it as soon as it appears it prints "got the focus", then if I Alt+Tab to another window and then back it prints it again: import sys from PyQt4 import QtGui, QtCore class EventFilter(QtCore.QObject): def __init__(self, parent=None): QtCore.QObject.__init__(self, parent) def eventFilter(self, obj, event): if event.type() == QtCore.QEvent.ActivationChange: if self.parent().isActiveWindow(): print "got the focus" return QtCore.QObject.eventFilter(self, obj, event) class TestWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.installEventFilter(EventFilter(self)) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Test Widget') quit = QtGui.QPushButton('Close', self) quit.setGeometry(10, 10, 60, 35) self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) tw = TestWidget() tw.show() sys.exit(app.exec_()) -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt
Re: [PyQt] a newbie pyqt question, the pyqt book related
On 2008-05-29, lotr py wrote: > Hi, Sorry for my bad english and PyQt skill. > I am reading the book "Rapid GUI Programming with Python and Qt The > Definitive Guide to PyQt Programming", my question is related to > chap08/mymovies.pyw. > near the end of MainWindow.updateTable() there is > if selected is not None: > selected.setSelected(True) > self.table.setCurrentItem(selected) > self.table.scrollToItem(selected) > what I want to ask is, what's the mean of "selected.setSelected(True)", > isn't self.table.setCurrentItem(selected) enough here? > Thank in advance for your reply. selected is either None or the QTableItem that we want to be selected. So if it is not None: selected.setSelected(True) # selects the item self.table.setCurrentItem(selected) # makes the item the current item self.table.scrollToItem(selected) # makes the item visible to the user In a QTableView it is possible to have a selected item that is not the current item, in other words there are two different concepts "selected item" and "current item". -- Mark Summerfield, Qtrac Ltd., www.qtrac.eu ___ PyQt mailing listPyQt@riverbankcomputing.com http://www.riverbankcomputing.com/mailman/listinfo/pyqt