I have a QGraphicsVideoItem added to a QGraphicsView widget. How can I crop the item so I don't see part of the displayed video? I have tried doing this:
class OverlayWidget(QWidget):
def __init__(self):
super().__init__()
scene = QGraphicsScene()
self.video_view = QGraphicsView(self)
self.video_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.video_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.video_view.setScene(scene)
player_1 = QMediaPlayer(self)
self.video_item_1 = QGraphicsVideoItem()
player_1.setVideoOutput(self.video_item_1)
scene.addItem(self.video_item_1)
# player_1.setSource("V.mp4")
# player_1.play()
player_2 = QMediaPlayer(self)
self.video_item_2 = QGraphicsVideoItem()
self.video_item_2.setAspectRatioMode(Qt.KeepAspectRatio)
player_2.setVideoOutput(self.video_item_2)
scene.addItem(self.video_item_2)
# player_2.setSource("V_compressed.mp4")
# player_2.play()
self.slider = QSlider(Qt.Horizontal, self)
self.slider.setStyleSheet("""
QSlider::groove:horizontal {
background: transparent;
}
QSlider::handle:horizontal {
background: white;
border: 1px solid black;
border-radius: 3px;
width: 10px;
}
""")
self.slider.valueChanged.connect(self.crop_video)
def resizeEvent(self, event):
super().resizeEvent(event)
self.video_view.resize(self.size())
self.slider.resize(self.size())
self.slider.setRange(0, self.video_view.width())
self.video_item_1.setSize(self.video_view.size())
self.video_item_2.setSize(self.video_view.size())
self.crop_video()
def crop_video(self):
# Crop the video substracting the slider right area
self.video_item_2.setPos(self.slider.value(), 0)
self.video_item_2.setOffset(QPoint(-self.slider.value(), 0))
But the part of the video that has negative X coordinate is still drawn. How can I hide it?
(I don't use QVideoWidget because I need to have the slider over the video, and it seems that the video is always on top of other widgets. I could use QVideoWidget if there is no other choice and put the slider outside the videos)
After a lot of trial error and wander through docs, I found that I could override paint method of a QGraphicsVideo item and set there the QPainter (setClipRect)
Full code:
from PySide6.QtCore import Qt, QRectF
from PySide6.QtGui import QPainter
from PySide6.QtMultimedia import QMediaPlayer
from PySide6.QtMultimediaWidgets import QGraphicsVideoItem
from PySide6.QtWidgets import (
QWidget,
QApplication,
QMainWindow,
QVBoxLayout,
QLabel,
QSlider,
QSizePolicy,
QGraphicsScene,
QGraphicsView,
QStyleOptionGraphicsItem,
)
class CustomItem(QGraphicsVideoItem):
def __init__(self):
super().__init__()
self.offset = 0
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget):
if self.offset != 0:
painter.setClipRect(QRectF(self.offset, 0, self.size().width(), self.size().height()))
QGraphicsVideoItem.paint(self, painter, option, widget)
class OverlayWidget(QWidget):
def __init__(self):
super().__init__()
scene = QGraphicsScene()
self.video_view = QGraphicsView(self)
self.video_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.video_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.video_view.setScene(scene)
player_1 = QMediaPlayer(self)
self.video_item_1 = CustomItem()
player_1.setVideoOutput(self.video_item_1)
scene.addItem(self.video_item_1)
# player_1.setSource("V.mp4") # Set here your video source
player_1.play()
player_2 = QMediaPlayer(self)
self.video_item_2 = CustomItem()
self.video_item_2.setAspectRatioMode(Qt.KeepAspectRatio)
player_2.setVideoOutput(self.video_item_2)
scene.addItem(self.video_item_2)
# player_2.setSource("V_compressed.mp4") # Set here your video source
player_2.play()
self.slider = QSlider(Qt.Horizontal, self)
self.slider.setStyleSheet("""
QSlider::groove:horizontal {
background: transparent;
}
QSlider::handle:horizontal {
background: white;
border: 1px solid black;
border-radius: 3px;
width: 10px;
}
""")
self.slider.valueChanged.connect(self.crop_video)
def resizeEvent(self, event):
super().resizeEvent(event)
self.video_view.resize(self.size())
self.slider.resize(self.size())
self.slider.setRange(0, self.video_view.width())
self.video_item_1.setSize(self.video_view.size())
self.video_item_2.setSize(self.video_view.size())
self.crop_video()
def crop_video(self):
# Crop the video substracting the slider left area
self.video_item_2.offset = self.slider.value()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.main_layout = QVBoxLayout()
self.central_widget.setLayout(self.main_layout)
self.label = QLabel("Overlay")
self.label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.main_layout.addWidget(self.label)
self.overlay_widget = OverlayWidget()
self.overlay_widget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
self.main_layout.addWidget(self.overlay_widget)
self.resize(800, 600)
if __name__ == "__main__":
app = QApplication()
window = MainWindow()
window.show()
app.exec()
Related
when i add pushbutton dynamically to the QGraphicScene with a pic its work but when i use QPainter to draw a line or rectangle not show.
code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import QIcon,QPixmap,QPainter,QPainterPath,QBrush,QColor,QPen
class Scene(QtWidgets.QGraphicsScene):
def __init__(self, *args, **kwargs):
super(Scene, self).__init__(*args, **kwargs)
self.path_item = self.addPath(QtGui.QPainterPath())
self.start_point = QtCore.QPointF()
self.end_point = QtCore.QPointF()
def mousePressEvent(self, event):
self.start_point = event.scenePos()
self.end_point = self.start_point
self.update_path()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if event.buttons() & QtCore.Qt.LeftButton:
self.end_point = event.scenePos()
self.update_path()
super(Scene, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self.end_point = event.scenePos()
self.update_path()
super(Scene, self).mouseReleaseEvent(event)
def update_path(self):
if not self.start_point.isNull() and not self.end_point.isNull():
path = QtGui.QPainterPath()
path.moveTo(self.start_point)
path.lineTo(self.end_point)
self.path_item.setPath(path)
def main():
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QGraphicsView()
view.setRenderHint(QtGui.QPainter.Antialiasing)
view.setMouseTracking(True)
pix = QPixmap('assets/data.png')
mainpic = QtWidgets.QGraphicsPixmapItem(pix)
scene = Scene()
scene.addItem(mainpic)
view.setScene(scene)
view.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I think my problem in mouse event but if i disable pic in GraphicsScene draw line correctly worked.
For some strange reason cannot override a highlighted text colour in QListView. It worked fine (a highlighted text colour is auto-changed to white) until I defined my own widget to represent a row.
Now I can change background colour and some other visual aspects of a selected row, but text colour always remains default black.
Already tried all possible with QSS, QPalette and data()/Qt.ForegroundRole - no trick helps.
Here is a simplified code, which still suffers from the issue on OS X. Unfortunately I had no chance to test on Windows or GNU/Linux.
from PySide.QtCore import *
from PySide.QtGui import *
import sys
view = None
mapp = {}
style = '''
QListView {
show-decoration-selected: 1;
selection-color: white;
selection-background-color: #0068d9;
}
QListView::item:selected:active:hover{
background-color:red; color: white;
}
QListView::item:selected:active:!hover{
background-color: #0068d9; color: white;
}
QListView::item:selected:!active{
background-color:yellow; color: white;
}
QListView::item:!selected:hover{
background-color:green; color: white;
}
'''
class SimpleListModel(QAbstractListModel):
def __init__(self, mlist):
QAbstractListModel.__init__(self)
self._items = mlist
def rowCount(self, parent = QModelIndex()):
return len(self._items)
def index(self, row, column, parent=QModelIndex()):
node = self._items[row]
if not(str(row) in mapp):
index = self.createIndex(row, column)
widget = QLabel(node)
view.setIndexWidget(index, widget)
mapp[str(row)] = index
return index
return mapp[str(row)]
def data(self, index, role = Qt.DisplayRole):
return None
def flags(self, index):
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
class MyMainWindow(QWidget):
def __init__(self):
global view
QWidget.__init__(self, None)
self._model = SimpleListModel(["test", "tes1t", "t3est", "t5est", "t3est"])
vbox = QVBoxLayout()
view = QListView()
view.setModel(self._model)
vbox.addWidget(view)
self.setLayout(vbox)
view.setStyleSheet(style)
first = self._model.index(0, 0)
view.setCurrentIndex(first)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyMainWindow()
w.show()
w.raise_()
app.exec_()
sys.exit()
Not the cleanest or best solution but this is what I came with after some tweaking.
Result:
The blue item is the selected one. The green item is the hovered one.
Code:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
view = None
mapp = {}
style = '''
QListView {
show-decoration-selected: 1;
selection-color: white;
selection-background-color: #0068d9;
}
QListView::item:selected:active:hover{
background-color:red; color: white;
}
QListView::item:selected:active:!hover{
background-color: #0068d9; color: white;
}
QListView::item:selected:!active{
background-color:yellow; color: white;
}
QListView::item:!selected:hover{
background-color:green; color: white;
}
'''
class SimpleListModel(QAbstractListModel):
def __init__(self, mlist):
QAbstractListModel.__init__(self)
self._items = mlist
def rowCount(self, parent = QModelIndex()):
return len(self._items)
def index(self, row, column, parent=QModelIndex()):
node = self._items[row]
if not(str(row) in mapp):
index = self.createIndex(row, column)
widget = QLabel(node)
view.setIndexWidget(index, widget)
mapp[str(row)] = index
return index
return mapp[str(row)]
def data(self, index, role = Qt.DisplayRole):
# The following code shouldn't be put in this function but i'm in a hurry right now...
selectedIndexes = view.selectedIndexes()
# Set all items to black
for i in range(0, self.rowCount()):
currentRowIndex = self.index(i, 0, QModelIndex())
myWidget = view.indexWidget(currentRowIndex)
myWidget.setStyleSheet("color: black")
# Set selected items to white
for i in selectedIndexes:
myWidget = view.indexWidget(i)
myWidget.setStyleSheet("color: white")
return None
def flags(self, index):
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
class MyMainWindow(QWidget):
def __init__(self):
global view
QWidget.__init__(self, None)
self._model = SimpleListModel(["test", "tes1t", "t3est", "t5est", "t3est"])
vbox = QVBoxLayout()
view = QListView()
view.setModel(self._model)
vbox.addWidget(view)
self.setLayout(vbox)
view.setStyleSheet(style)
first = self._model.index(0, 0)
view.setCurrentIndex(first)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyMainWindow()
w.show()
w.raise_()
app.exec_()
sys.exit()
Please let me know if there's something I didn't understand correctly or the code is not clear enough.
First:
Your code is working on GNU/Linux (Ubuntu 14.04 LTS, PyQt5) in the same way.
Since text is written to indexWidget, stylesheet for the text-color must be set for QLabel.
As QLabel does not support the hover pseudostate, it can not be done in the same way as for the items.
To set stylesheet for selected indexWidgets I used signal-slot-mechanism, for hovered indexWidgets I used event filter,
only class MyMainWindow modified:
class MyMainWindow(QWidget):
def __init__(self):
global view
QWidget.__init__(self, None)
self._model = SimpleListModel(["test", "tes1t", "t3est", "t5est", "t3est"])
vbox = QVBoxLayout()
view = QListView()
view.setModel(self._model)
view.setMouseTracking(True) # to catch mouseEvents
view.installEventFilter(self) # for events in ListView
vbox.addWidget(view)
self.setLayout(vbox)
view.setStyleSheet(style)
first = self._model.index(0, 0)
view.setCurrentIndex(first)
view.clicked.connect(self.setIndexStyle) # or any other signal
def setIndexStyle(self, index):
for i in range(0,view.model().rowCount()):
style = 'color: black;'
view.indexWidget(view.model().index(i,0)).setStyleSheet(style)
for i in view.selectedIndexes(): # works for multiseletion too
style = 'color: white;'
view.indexWidget(i).setStyleSheet(style)
def eventFilter(self,obj,event):
if event.type() == QEvent.HoverMove and isinstance(obj,QListView):
i = view.indexAt(event.pos()) # index at mouse.pos()
self.setIndexStyle(i) # selected indexWidgets still have white text
style = 'color: white;'
try: # if no item on mouse.pos()
view.indexWidget(i).setStyleSheet(style)
except AttributeError:
pass
return False
return QWidget.eventFilter(self,obj,event)
I tried:
self.installEventFilter(self)
and:
desktop= QApplication.desktop()
desktop.installEventFilter(self)
With:
def eventFilter(self, source, event):
if event.type() == QEvent.MouseMove:
print(event.pos())
return QMainWindow.eventFilter(self, source, event)
In QMainWindow object but nothing conclusive.
Do you have any idea?
Mouse events are initially handled by the window-manager, which then passes them on to whatever window is in that region of the screen. So if there are no Qt windows in that region, you won't get any events (including mouse events).
However, it is still possible to track the cursor position via polling:
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
cursorMove = QtCore.pyqtSignal(object)
def __init__(self):
super(Window, self).__init__()
self.cursorMove.connect(self.handleCursorMove)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(50)
self.timer.timeout.connect(self.pollCursor)
self.timer.start()
self.cursor = None
def pollCursor(self):
pos = QtGui.QCursor.pos()
if pos != self.cursor:
self.cursor = pos
self.cursorMove.emit(pos)
def handleCursorMove(self, pos):
print(pos)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 500, 200, 200)
window.show()
sys.exit(app.exec_())
I have a label that sometimes contain a long text with no spaces (path in the computer).
So word-wrap wraps it very weirdly.
Is there a way to make the word-wrap of the label break in the middle of the word or not only at white spaces?
This isn't elegant but does work...
So say header class has Private:
QLabel *thisLabel;
QString *pathName;
QString *pathNameClean;
and of course defining thisLabel some where.
so it would be nice if it was this simple....
thisLabel->setWordWrap(true);
that's fine IF AND ONLY IF the word has break points
(WHICH PATHS SHOULD AVOID)
SO keep your actual path in a separate string if you need it for QFile purposes later.
Then manually define a character per line number, and insert the spaces into the string....
so we'll say 50 chars is a good width...
pathNameClean = new QString(pathName);
int c = pathName->length();
if( c > 50)
{
for(int i = 1; i <= c/50; i++)
{
int n = i * 50;
pathName->insert(n, " ");
}
}
thisLabel->setText(pathName);
Shazam.... simulated WordWrap with no original spaces...
just remember that pathName string is now just for pretty QLabel purposes and that the pathNameClean string is the actual path. Qt programs will crash if you try to open a file with a space injected path.....
(if there's no simple class method it's likely just a few lines of code to do...
and why problem solving is a programmers best tool!)
One way is to use the QTextOption class with a QTextDocument instead of a QLabel. This let you use QTextOption::WrapMode. QTextOption::WrapAtWordBoundaryOrAnywhere should do what you want.
QLabel with other wrap mode
I happen to have this same question in 2021, so I here I will share with you some of the best answers I have found so far.
TextWrapAnywhere QLabel
Subclass QLabel and and implement the paintEvent, where you can set the text alignment to TextWrapAnywhere when you drawItemText.
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QStyleOption, QVBoxLayout, QWidget, QStyle
class SuperQLabel(QLabel):
def __init__(self, *args, **kwargs):
super(SuperQLabel, self).__init__(*args, **kwargs)
self.textalignment = Qt.AlignLeft | Qt.TextWrapAnywhere
self.isTextLabel = True
self.align = None
def paintEvent(self, event):
opt = QStyleOption()
opt.initFrom(self)
painter = QPainter(self)
self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)
self.style().drawItemText(painter, self.rect(),
self.textalignment, self.palette(), True, self.text())
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setFixedSize(100, 200)
self.label = QLabel()
self.label.setWordWrap(True)
self.label.setText("1111111111111111111111111111")
self.slabel = SuperQLabel()
self.slabel.setText("111111111111111111111111111")
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.mainlayout = QVBoxLayout()
self.mainlayout.addWidget(self.label)
self.mainlayout.addWidget(self.slabel)
self.centralwidget.setLayout(self.mainlayout)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Text Wrap at char instead of white space
According to this answer(in op's comment) provided by #ekhumoro, if you are looking for wrapping a line based on comma, you can insert a zero-width-space after the char you want to wrap and use the built in word wrap function.
Here is an example:
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QStyleOption, QStylePainter, QVBoxLayout, QWidget, QStyle
class CommaWrapableQLabel(QLabel):
def __init__(self, *args, **kwargs):
super(CommaWrapableQLabel, self).__init__(*args, **kwargs)
def setWordWrapAtAnychar(self, char):
newtext = self.text().replace(char, f"{char}\u200b")
self.setText(newtext)
self.setWordWrap(True)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setFixedSize(100, 200)
self.label = QLabel()
self.label.setWordWrap(True)
self.label.setText(
'Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window')
self.slabel = CommaWrapableQLabel()
self.slabel.setText(
'Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window')
self.slabel.setWordWrapAtAnychar(",")
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.mainlayout = QVBoxLayout()
self.mainlayout.addWidget(self.label)
self.mainlayout.addWidget(self.slabel)
self.centralwidget.setLayout(self.mainlayout)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Black magic solution
As said from other answers, you can reimplement paintEvent() for QLabel to pass the Qt::TextWrapAnywhere flag.
However, overriding paintEvent() may cause unexpected side effects since the default implementation of paintEvent() contains a lot of extra features besides just painting the text as is.
Actually the alignment flags passed to QStyle::drawItemText is stored in a private member QLabelPrivate::align. I came up with the idea to force rewrite the value of it with the Qt::TextWrapAnywhere flag set, and it works. This workaround requires a bit of C++ black magic.
class WorkaroundLabel: public QLabel {
Q_OBJECT
public:
WorkaroundLabel(QString text, QWidget* parent): QLabel(text, parent) {
setWordWrap(true);
ushort* p;
if (FindAlignAddr(&p)) {
*p = (*p | Qt::TextWrapAnywhere);
} else {
// workaround failed
}
}
virtual ~WorkaroundLabel() {}
protected:
// "ushort align;" in qtbase/src/widgets/widgets/qlabel_p.h
bool FindAlignAddr(ushort** out) {
Qt::Alignment align = alignment();
void* d_raw = (void*) d_ptr.data();
ushort* p = reinterpret_cast<ushort*>(d_raw);
for (int i = 0; i < 1024; i += 1) {
setAlignment(Qt::AlignLeft);
ushort a = *p;
setAlignment(Qt::AlignRight);
ushort b = *p;
if (a != b) {
*out = p;
setAlignment(align);
return true;
}
p++;
}
setAlignment(align);
return false;
}
};
In 2020, PySide2, it is just:
tmp = QLabel()
tmp.setWordWrap(True)
I am writing an application that allows a user to place images on a QGraphicsScene (contained within a QGraphicsView) by clicking on a blank area and then move them about using mousemoveevent. The images are created using a subclassed QGraphicsPixmapItem.
Here's the problem: The very first attempt at moving an item works as expected. However, for all subsequent moves the selected item immediately jumps to the upper left corner of the scene. Here is the code:
import sys
from PySide import QtGui,QtCore
class TestPixmapItem(QtGui.QGraphicsPixmapItem):
def __init__(self, imagename, position, parent=None):
QtGui.QGraphicsPixmapItem.__init__(self, parent)
px = QtGui.QPixmap(imagename)
self.setPixmap(px)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
# set position
self.setPos(position.x(),position.y())
def mouseReleaseEvent(self,e):
self.setSelected(False)
def mouseMoveEvent(self, e):
QtGui.QGraphicsPixmapItem.mouseMoveEvent(self, e)
class GfxScene(QtGui.QGraphicsScene):
def __init__(self, parent=None):
#build parent user interface
super(GfxScene, self).__init__(parent)
def mousePressEvent(self, e):
if(self.itemAt(e.scenePos().x(),e.scenePos().y()) == None):
pixmapItem = TestPixmapItem('test.png',e.scenePos())
self.addItem(pixmapItem)
else:
QtGui.QGraphicsScene.mousePressEvent(self,e);
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
scene = GfxScene(self)
scene.setSceneRect(QtCore.QRect(0, 0, 800, 800))
view = QtGui.QGraphicsView()
view.setScene(scene)
view.setSceneRect(scene.sceneRect())
#view.setGeometry(QtCore.QRect(0, 0, 800, 800))
self.setCentralWidget(view)
def main():
#This function means this was run directly, not called from another python file.
app = QtGui.QApplication.instance()
if app == None:
app = QtGui.QApplication(sys.argv)
myapp = MainForm()
myapp.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Any help would be appreciated!
You should call the QtGui.QGraphicsPixmapItem.mouseReleaseEvent(self, e) when you override the mouse release event, see : http://goo.gl/ChSYP
import sys
from PySide import QtGui,QtCore
class TestPixmapItem(QtGui.QGraphicsPixmapItem):
def __init__(self, imagename, position, parent=None):
QtGui.QGraphicsPixmapItem.__init__(self, parent)
px = QtGui.QPixmap(imagename)
self.setPixmap(px)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
# set position
self.setPos(position.x(),position.y())
def mouseReleaseEvent(self,e):
self.setSelected(False)
QtGui.QGraphicsPixmapItem.mouseReleaseEvent(self, e) // here calling the event
def mouseMoveEvent(self, e):
QtGui.QGraphicsPixmapItem.mouseMoveEvent(self, e)
class GfxScene(QtGui.QGraphicsScene):
def __init__(self, parent=None):
#build parent user interface
super(GfxScene, self).__init__(parent)
def mousePressEvent(self, e):
if(self.itemAt(e.scenePos().x(),e.scenePos().y()) == None):
pixmapItem = TestPixmapItem('test.png',e.scenePos())
self.addItem(pixmapItem)
else:
QtGui.QGraphicsScene.mousePressEvent(self,e);
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
scene = GfxScene(self)
scene.setSceneRect(QtCore.QRect(0, 0, 800, 800))
view = QtGui.QGraphicsView()
view.setScene(scene)
view.setSceneRect(scene.sceneRect())
#view.setGeometry(QtCore.QRect(0, 0, 800, 800))
self.setCentralWidget(view)
def main():
#This function means this was run directly, not called from another python file.
app = QtGui.QApplication.instance()
if app == None:
app = QtGui.QApplication(sys.argv)
myapp = MainForm()
myapp.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()