[PyQt] QGraphicsView item select

Vincent Vande Vyvre vincent.vandevyvre at swing.be
Wed Apr 11 15:13:09 BST 2012


Le 11/04/12 15:46, Alfredo Junior a écrit :
> OK, I'll try.
>
> Thank you.
>
> ----- Original Message -----
> From: Andreas Pakulat <apaku at gmx.de>
> To: "pyqt at riverbankcomputing.com" <pyqt at riverbankcomputing.com>
> Cc: 
> Sent: Wednesday, April 11, 2012 10:28 AM
> Subject: Re: [PyQt] QGraphicsView item select
>
> On 11.04.12 06:02:09, Alfredo Junior wrote:
>> OK.
>>
>> This is a functional example:
>>
>> #!/usr/bin/python
>> # -*- coding: utf-8 -*-
>>
>> import sys
>> from PyQt4.QtCore import *
>> from PyQt4.QtGui import *
>>
>> def itemSelected(self):
>>     print "Selection changed"
>>     
>> app = QApplication(sys.argv)
>> grview = QGraphicsView()
>> scene = QGraphicsScene()
>> scene.addPixmap(QPixmap('on.png'))
>> grview.setScene(scene)
>> scene.selectionChanged.connect(itemSelected)
>> grview.show()
>> sys.exit(app.exec_())
>>
>> It should run the function itemSelected and print "Selection changed" when I click on the picture (little green square).
> Indeed this example does not trigger the the selection change signal. In
> the docs of the signal is a pointer to QGraphicsItem::setSelected and a
> pointer to QGraphicsScene::setSelectionArea and both functions document
> that items are not selectable by default, so it needs to be enabled by
> setting the corresponding flag on the item.
>
> Andreas
>
> _______________________________________________
> PyQt mailing list    PyQt at riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt
>
> _______________________________________________
> PyQt mailing list    PyQt at riverbankcomputing.com
> http://www.riverbankcomputing.com/mailman/listinfo/pyqt
>
You'll be more easy if you subclass your QGraphicsPixmapItem.

Example: the item can return his index, or name or identifier, etc.

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class GameItem(QGraphicsPixmapItem):
    def __init__(self, idx, img, parent=None, scene=None):
        super(GameItem, self).__init__(parent, scene)
        self.idx = idx
        self.setPixmap(QPixmap(img))

    def mousePressEvent(self, event):
        self.itemSelected(self.idx)

    def itemSelected(self, what):
        print "item {0} clicked".format(self.idx)
   
app = QApplication(sys.argv)
grview = QGraphicsView()
scene = QGraphicsScene()
item = GameItem(0, 'on.png', None, scene)
grview.setScene(scene)
grview.show()
sys.exit(app.exec_())

VVV

-- 
Vincent V.V.
Oqapy <https://launchpad.net/oqapy> . Qarte+7
<https://launchpad.net/qarte+7> . PaQager <https://launchpad.net/paqager>



More information about the PyQt mailing list