Pyside Qmenu Examples - python

Does anyone know examples about how to change a qMenu styles of lines separately ( change color of text of line , color of line bg, add underline to any texts inside texts etc. ) or if can't be done , can be solved anyhow ?
Thanks,
Szabolcs
share my code:
class MainWindow(QtGui.QMainWindow):
def init(self):
super(MainWindow, self).init()
self.menus = ['alma','korte','banan','ezmegaz']
acts = []
self.qmenu = QtGui.QMenu()
self.hip_fgrp = HipFileGroup( hip_data_file )
self.hip_fgrp.RemoveRepeats()
for i,hipf in enumerate(self.hip_fgrp.hipFileArr):
short_n = hipf.shortname
# prj = hipf.shortprjname
prj = ''
prj = hipf.shortprjname
if len(hipf.add_hipfolders):
prj = prj + ' \\ ' + hipf.add_hipfolders[0]
action = QtGui.QAction( prj+' \\ '+short_n, self, triggered=self.MenuSelected)
action.setData( i)
acts.append( action)
# print short_n
mpos = QtGui.QCursor
x = mpos.pos().x()
y = mpos.pos().y()
for action in acts:
self.qmenu.addAction(action)
self.qmenu.show()
self.qmenu.setGeometry( x-20, y-20, 0, 0)
self.qmenu.exec_()
def MenuSelected( self):
action = self.sender()
hipfile_id = action.data()
hipfile = self.hip_fgrp.hipFileArr[ hipfile_id]
hipfile.show_all()
hipfile_last = hipfile.getLastVersion( hipfile.hipfullspec)
print hipfile_last
if not in_sublime:
import hou
hou.hipFile.load( hipfile_last, hip_accept)

I don't know of any easy way. And it seems to be a long-standing question. But almost anything is possible with a bit of work:
Rather than using a QAction in your menu you can use a QWidgetAction which lets you customise the widget used to represent the action in the menu. Here I use a QLabel which supports rich text. However, bear in mind that the widget needs to handle the mouse itself (here I call trigger).
import sys
from PySide import QtGui
class MyLabel(QtGui.QLabel):
def __init__(self,action):
super(MyLabel,self).__init__()
self.action = action
def mouseReleaseEvent(self,e):
self.action.trigger()
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
wAction = QtGui.QWidgetAction(self)
ql = MyLabel(wAction)
ql.setText("<b>Hello</b> <i>Qt!</i>")
wAction.setDefaultWidget(ql)
wAction.triggered.connect(self.close)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(wAction)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Menubar')
self.show()
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
In a more fully featured example you might subclass QWidgetAction to handle different action contexts, and use different widgets, but this should get you started.

Related

PyQt5 removing button

In the list_widget I have added a add button I also want to add a remove button which asks which item you wants to remove and remove the chosen item. I was trying it to do but I didn't had any idea to do so .Also, please explain the solution I am a beginner with pyqt5 or I'd like to say absolute beginner.
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication,QMainWindow,
QListWidget, QListWidgetItem
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.x = 200
self.y = 200
self.width = 500
self.length = 500
self.setGeometry(self.x, self.y, self.width,
self.length)
self.setWindowTitle("Stock managment")
self.iniTUI()
def iniTUI(self):
# buttons
self.b1 = QtWidgets.QPushButton(self)
self.b1.setText("+")
self.b1.move(450, 100)
self.b1.resize(50, 25)
self.b1.clicked.connect(self.take_inputs)
# This is the button I want to define.
self.btn_minus = QtWidgets.QPushButton(self)
self.btn_minus.setText("-")
self.btn_minus.move(0, 100)
self.btn_minus.resize(50, 25)
# list
self.list_widget = QListWidget(self)
self.list_widget.setGeometry(120, 100, 250, 300)
self.item1 = QListWidgetItem("A")
self.item2 = QListWidgetItem("B")
self.item3 = QListWidgetItem("C")
self.list_widget.addItem(self.item1)
self.list_widget.addItem(self.item2)
self.list_widget.addItem(self.item3)
self.list_widget.setCurrentItem(self.item2)
def take_inputs(self):
self.name, self.done1 =
QtWidgets.QInputDialog.getText(
self, 'Add Item to List', 'Enter The Item you want
in
the list:')
self.roll, self.done2 = QtWidgets.QInputDialog.getInt(
self, f'Quantity of {str(self.name)}', f'Enter
Quantity of {str(self.name)}:')
if self.done1 and self.done2:
self.item4 = QListWidgetItem(f"{str(self.name)}
Quantity{self.roll}")
self.list_widget.addItem(self.item4)
self.list_widget.setCurrentItem(self.item4)
def clicked(self):
self.label.setText("You clicked the button")
self.update()
def update(self):
self.label.adjustSize()
def clicked():
print("meow")
def window():
apk = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(apk.exec_())
window()
The core issue here is the lack of separation of the view and the data. This makes it very hard to reason about how to work with graphical elements. You will almost certainly want to follow the Model View Controller design paradigm https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
which offers a systematic way to handle this separation.
Once you do so, it immediately becomes very straight forward how to proceed with the question: You essentially just have a list, and you either want to add a thing to this list, or remove one based on a selection.
I include an example here which happens to use the built-in classes QStringListModel and QListView in Qt5, but it is simple to write your own more specialized widgets and models. They all just use a simple signal to emit to the view that it needs to refresh the active information.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class StuffViewer(QMainWindow):
def __init__(self, model):
super().__init__()
self.setWindowTitle("Stock managment")
# 1: Use layouts.
hbox = QHBoxLayout()
widget = QWidget()
widget.setLayout(hbox)
self.setCentralWidget(widget)
# 2: Don't needlessly store things in "self"
vbox = QVBoxLayout()
add = QPushButton("+")
add.clicked.connect(self.add_new_stuff)
vbox.addWidget(add)
sub = QPushButton("-")
sub.clicked.connect(self.remove_selected_stuff)
vbox.addWidget(sub)
vbox.addStretch(1)
hbox.addLayout(vbox)
# 3: Separate the view of the data from the data itself. Use Model-View-Controller design to achieve this.
self.model = model
self.stuffview = QListView()
self.stuffview.setModel(self.model)
hbox.addWidget(self.stuffview)
def add_new_stuff(self):
new_stuff, success = QInputDialog.getText(self, 'Add stuff', 'Enter new stuff you want')
if success:
self.stuff.setStringList(self.stuff.stringList() + [new_stuff])
def remove_selected_stuff(self):
index = self.stuffview.currentIndex()
all_stuff = self.stuff.stringList()
del all_stuff[index.column()]
self.stuff.setStringList(all_stuff)
def window():
apk = QApplication(sys.argv)
# Data is clearly separated:
# 4: Never enumerate variables! Use lists!
stuff = QStringListModel(["Foo", "Bar", "Baz"])
# The graphical components is just how you interface with the data with the user!
win = StuffViewer(stuff)
win.show()
sys.exit(apk.exec_())
window()

Complex context-menu submenu

I have a Qt5 application mainly driven by context menu.
Right now I have the standard structure with menu(s), submenu(s) and actions.
I would like to add, in place of a submenu, a small dialog with a few input widgets, something like this:
Is there any (possibly simple) way to get this?
I know I can open a normal dialog from popup, but that is not what I mean.
I would like to have normal submenu behavior, with chance to go back to parent menu... if possible.
Note: I'm actually using PyQt5, but I think this is a more general Qt question.
Following #G.M. advice I was able to partially solve my problem.
My code current code looks like:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class ActionFont(QWidgetAction):
def __init__(self, parent: QWidget, target: QPlainTextEdit):
super(ActionFont, self).__init__(parent)
self.setIcon(QIcon("font-face.svg"))
self.setText("Face")
w = QFontComboBox()
w.currentFontChanged.connect(self.doit)
self.setDefaultWidget(w)
self.cursor = target.textCursor()
self.char_format = self.cursor.charFormat()
font = self.char_format.font()
w.setCurrentFont(font)
# self.triggered.connect(self.doit)
def doit(self, font):
self.char_format.setFont(font)
self.cursor.setCharFormat(self.char_format)
class ActionSize(QWidgetAction):
def __init__(self, parent: QWidget, target: QPlainTextEdit):
super(ActionSize, self).__init__(parent)
self.setIcon(QIcon("font-size.svg"))
self.setText("Size")
self.has_changed = False
w = QSpinBox()
self.setDefaultWidget(w)
self.cursor = target.textCursor()
self.char_format = self.cursor.charFormat()
font = self.char_format.font()
size = font.pointSize()
w.setRange(6, 100)
w.setValue(size)
w.valueChanged.connect(self.doit)
w.editingFinished.connect(self.quit)
def doit(self, size):
print(f'ActionSize.doit({size})')
self.char_format.setFontPointSize(size)
self.cursor.setCharFormat(self.char_format)
self.has_changed = True
def quit(self):
print(f'ActionSize.quit()')
if self.has_changed:
print(f'ActionSize.quit(quitting)')
class Window(QMainWindow):
def __init__(self, parent=None):
from lorem import text
super().__init__(parent)
self.text = QPlainTextEdit(self)
self.setCentralWidget(self.text)
self.text.setContextMenuPolicy(Qt.CustomContextMenu)
self.text.customContextMenuRequested.connect(self.context)
self.text.appendPlainText(text())
self.setGeometry(100, 100, 1030, 800)
self.setWindowTitle("Writer")
def context(self, pos):
m = QMenu(self)
w = QComboBox()
w.addItems(list('ABCDE'))
wa = QWidgetAction(self)
wa.setDefaultWidget(w)
m.addAction('Some action')
m.addAction(wa)
m.addAction('Some other action')
sub = QMenu(m)
sub.setTitle('Font')
sub.addAction(ActionFont(self, self.text))
sub.addAction(ActionSize(self, self.text))
m.addMenu(sub)
pos = self.mapToGlobal(pos)
m.move(pos)
m.show()
app = QApplication([])
w = Window()
w.show()
app.exec()
This works with a few limitations:
I have been able to add just a single widget using setDefaultWidget(), if I try to
add a fill QWidget or a container (e.g.: QFrame) nothing appears in menu.
I have therefore not been able to prepend an icon (or a QLabel) to the widget.
Widget does not behave like a menu item (it does not close when activated); I tried to overcome that as implemented in ActionSize, but looks rather kludgy and I'm unsure if it's the right way to go.
I will therefore not accept my own answer in hope someone can refine it enough to be generally useful.

Why won't QToolTips appear on QActions within a QMenu

I'm doing an app with in GUI written with PySide. I set a QMenu on a QPushButton, added several QActions via QMenu.addAction. To further explain these actions to the user I added QToolTip's to these with QAction.setToolTip.
When I run the GUI now my QToolTip won't show. The example posted below reproduces the same issue, any ideas?
Thanks in advance
import sys
from PySide import QtGui
class Example(QtGui.QPushButton):
def __init__(self, parent = None):
super(Example, self).__init__(parent)
self.setText('TestMenu')
self.setToolTip('This is a Test Button')
menu = QtGui.QMenu(self)
action_1 = menu.addAction('Action1')
action_1.setToolTip('This is action 1')
action_2 = menu.addAction('Action2')
action_2.setToolTip('This is action 2')
action_3 = menu.addAction('Action3')
action_3.setToolTip('This is action 3')
action_4 = menu.addAction('Action4')
action_4.setToolTip('This is action 4')
self.setMenu(menu)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
app.exec_()
if __name__ == '__main__':
main()
In Qt-5.1 or later, you can simply use QMenu.setToolTipsVisible, and the menu items will show their tooltips as expected (see QTBUG-13663):
menu.setToolTipsVisible(True)
However, for Qt-4.* and Qt-5.0, the situation is different. If an action is added to a toolbar, its tooltip will be shown; but if the same action is added to a QMenu, it won't be, and there is no built-in API to change that. There are a couple of ways to work around this. One is to use status tips instead, which will show the menu-item information in the status-bar. The other is to implement the menu-item tooltip functionality yourself using the QMenu.hovered signal and QToolTip.showText:
self.menu = QtGui.QMenu(self)
...
self.menu.hovered.connect(self.handleMenuHovered)
def handleMenuHovered(self, action):
QtGui.QToolTip.showText(
QtGui.QCursor.pos(), action.toolTip(),
self.menu, self.menu.actionGeometry(action))
Actually you don't have to do any workaround to display your tooltip, since Qt 5.1, you can use QMenu's property toolTipsVisible, which is by default set to false.
See the related Qt suggestion.
With ekhumoro helping me on the way got to this solution. It's probably not the most beautiful thing, and the code below positions the menu and the tool tips somewhat arkward, but in my actual programm it looks quite neat.
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QPushButton):
def __init__(self, parent = None):
super(Example, self).__init__(parent)
self.setText('TestMenu')
self.setToolTip('This is a Test Button')
menu = QtGui.QMenu(self)
action_1 = menu.addAction('Action1')
action_1.setToolTip('This is action 1')
action_2 = menu.addAction('Action2')
action_2.setToolTip('This is action 2')
action_3 = menu.addAction('Action3')
action_3.setToolTip('This is action 3')
action_4 = menu.addAction('Action4')
action_4.setToolTip('This is action 4')
action_1.hovered.connect(lambda pos = [self], parent = action_1, index = 0: show_toolTip(pos, parent, index))
action_2.hovered.connect(lambda pos = [self], parent = action_2, index = 1: show_toolTip(pos, parent, index))
action_3.hovered.connect(lambda pos = [self], parent = action_3, index = 2: show_toolTip(pos, parent, index))
action_4.hovered.connect(lambda pos = [self], parent = action_4, index = 3: show_toolTip(pos, parent, index))
self.setMenu(menu)
self.show()
def show_toolTip(pos, parent, index):
'''
**Parameters**
pos: list
list of all parent widget up to the upmost
parent: PySide.QtGui.QAction
the parent QAction
index: int
place within the QMenu, beginning with zero
'''
position_x = 0
position_y = 0
for widget in pos:
position_x += widget.pos().x()
position_y += widget.pos().y()
point = QtCore.QPoint()
point.setX(position_x)
point.setY(position_y + index * 22) # set y Position of QToolTip
QtGui.QToolTip.showText(point, parent.toolTip())
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
app.exec_()
if __name__ == '__main__':
main()
I have to say I'm not perfectly happy with this, mainly because the show_toolTip function has to be global, for the lambda operator didn't recognize it when I had it in the class (self.show_toolTip). I'm still open for suggesetions if someone has a suggestion.
Instead of showing tooltip immediately one can just update the tooltip of the parent (menu) when hovering and wait for the tooltip to be shown! Therefore:
menu = QtGui.QMenu(self)
action_1 = menu.addAction('Action1')
action_1.setToolTip('This is action 1')
...
menu.hovered.connect(self.handleMenuHovered)
def handleMenuHovered(self, action):
action.parent().setToolTip(action.toolTip())

Removing thin borders between widgets in Qt

In particular I have 2 questions:
1) How can I remove those thin lines between the widgets? setMargin(0) and setSpacing(0)
are already set.
2) In a further step I want to remove the window title bar with FramelessWindowHint.
To drag the window, I'll bind a mouseevent on the upper dark yellow widget. Right now, the upper widget is a QTextEdit with suppressed keyboard interactions. For the draging purpose, I doubt this widget is good... So the question is, what other widgets are good to create a colored handle to drag the window? Perhaps QLabel?
EDIT: Here is the code. I only used QTestEdit-Widgets.
from PyQt4.QtGui import *
from PyQt4 import QtGui,QtCore
import sys
class Note(QWidget):
def __init__(self, parent = None):
super(QWidget, self).__init__(parent)
self.createLayout()
self.setWindowTitle("Note")
def createLayout(self):
textedit = QTextEdit()
grip = QTextEdit()
grip.setMaximumHeight(16) #reduces the upper text widget to a height to look like a grip of a note
grip.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) #suppresses the scroll bar that appears under a certain height
empty = QTextEdit()
empty.setMaximumHeight(16)
empty.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
resize = QTextEdit()
resize.setMaximumHeight(16)
resize.setMaximumWidth(16)
resize.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
layout = QVBoxLayout()
layout.addWidget(grip)
layout.addWidget(textedit)
layout.setMargin(0)
layout.setSpacing(0)
layoutBottom=QHBoxLayout()
layoutBottom.addWidget(empty)
layoutBottom.addWidget(resize)
layout.addLayout(layoutBottom)
self.setLayout(layout)
# Set Font
textedit.setFont(QFont("Arial",16))
# Set Color
pal=QtGui.QPalette()
rgb=QtGui.QColor(232,223,80) #Textwidget BG = yellow
pal.setColor(QtGui.QPalette.Base,rgb)
textc=QtGui.QColor(0,0,0)
pal.setColor(QtGui.QPalette.Text,textc)
textedit.setPalette(pal)
empty.setPalette(pal)
pal_grip=QtGui.QPalette()
rgb_grip = QtGui.QColor(217,207,45)
pal_grip.setColor(QtGui.QPalette.Base,rgb_grip)
textc_grip=QtGui.QColor(0,0,0)
pal.setColor(QtGui.QPalette.Text,textc_grip)
grip.setPalette(pal_grip)
resize.setPalette(pal_grip)
resize.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
empty.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
grip.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
#textedit.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) #total text widget lock
#textedit.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) #Lock?
#http://qt-project.org/doc/qt-4.8/qt.html#TextInteractionFlag-enum
#self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #removes the title bar
#self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) #to make the window stay on top
class Main():
def __init__(self):
self.notes=[]
self.app = QApplication(sys.argv)
self.app.setQuitOnLastWindowClosed(False);
self.trayIcon = QSystemTrayIcon(QIcon(r"C:\Users\Thomas\Desktop\SimpleNotes.ico"), self.app)
self.menu = QMenu()
self.newWindow = self.menu.addAction("New note")
self.separator = self.menu.addSeparator()
self.hideNotes = self.menu.addAction("Hide all notes")
self.showNotes = self.menu.addAction("Show all notes")
self.separator = self.menu.addSeparator()
self.saveNotes = self.menu.addAction("Save notes")
self.loadNotes = self.menu.addAction("Load notes")
self.separator = self.menu.addSeparator()
self.showHelp = self.menu.addAction("Show help")
self.showAbout = self.menu.addAction("Show about")
self.separator = self.menu.addSeparator()
self.exitAction = self.menu.addAction("Quit notes")
self.exitAction.triggered.connect(self.close)
self.newWindow.triggered.connect(self.newNote)
self.trayIcon.setContextMenu(self.menu)
self.trayIcon.show()
self.app.exec()
def newNote(self):
print("Create new note entry has been clicked")
note=Note()
note.show()
self.notes.append(note)
print(self.notes)
def hideNotes(self):
pass
def showNotes(self):
pass
def saveNotes(self):
pass
def loadNotes(self):
pass
def showHelp(self):
pass
def showAbout(self):
pass
def close(self):
self.trayIcon.hide()
self.app.exit()
print("Exit menu entry has been clicked")
if __name__ == '__main__':
Main()
The answer from thuga was good enough, so i post it here:
textedit.setFrameShape(QtGui.QFrame.NoFrame)
and
grip.setFrameShape(QtGui.QFrame.NoFrame)
made the line disappear.
for 1. I've used:
textEdit.setFrameStyle(QtGui.QFrame.NoFrame)
ui->fr200->setFrameShape(QFrame::NoFrame);
ui->fr201->setFrameShape(QFrame::NoFrame);
ui->fr202->setFrameShape(QFrame::NoFrame);
ui->fr203->setFrameShape(QFrame::NoFrame);
ui->fr204->setFrameShape(QFrame::NoFrame);
ui->fr205->setFrameShape(QFrame::NoFrame);
ui->fr206->setFrameShape(QFrame::NoFrame);
ui->fr207->setFrameShape(QFrame::NoFrame);
ui->fr208->setFrameShape(QFrame::NoFrame);

QGraphicsView not displaying QGraphicsItems

Using PyQt4.
My goal is to load in "parts" of a .png, assign them to QGraphicsItems, add them to the scene, and have the QGraphicsView display them. (Right now I don't care about their coordinates, all I care about is getting the darn thing to work).
Currently nothing is displayed. At first I thought it was a problem with items being added and QGraphicsView not updating, but after reading up a bit more on viewports, that didn't really make sense. So I tested adding the QGraphicsView items before even setting the view (so I know it wouldn't be an update problem) and it still displayed nothing. The path is definitely correct. Here is some code that shows what is going on...
Ignore spacing issues, layout got messed up when pasting
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.setWindowTitle('NT State Editor')
winWidth = 1024
winHeight = 768
screen = QtGui.QDesktopWidget().availableGeometry()
screenCenterX = (screen.width() - winWidth) / 2
screenCenterY = (screen.height() - winHeight) / 2
self.setGeometry(screenCenterX, screenCenterY, winWidth, winHeight)
self.tileMap = tilemap.TileMap()
self.tileBar = tilebar.TileBar()
mapView = QtGui.QGraphicsView(self.tileMap)
tileBarView = QtGui.QGraphicsView(self.tileBar)
button = tilebar.LoadTilesButton()
QtCore.QObject.connect(button, QtCore.SIGNAL('selectedFile'),
self.tileBar.loadTiles)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(mapView)
hbox.addWidget(self.tileBarView)
hbox.addWidget(button)
mainWidget = QtGui.QWidget()
mainWidget.setLayout(hbox)
self.setCentralWidget(mainWidget)
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
--
class Tile(QtGui.QGraphicsPixmapItem):
def __init__(self, parent = None):
QtGui.QGraphicsPixmapItem(self, parent)
self.idAttr = -1
class TileBar(QtGui.QGraphicsScene):
def __init__(self, parent = None):
QtGui.QGraphicsScene.__init__(self, parent)
def loadTiles(self, filename):
tree = ElementTree()
tree.parse(filename)
root = tree.getroot()
sheets = root.findall('sheet')
for sheet in sheets:
sheetPath = sheet.get('path')
sheetImg = QtGui.QImage(sheetPath)
strips = sheet.findall('strip')
for strip in strips:
tile = Tile()
tile.idAttr = strip.get('id')
clip = strip.find('clip')
x = clip.get('x')
y = clip.get('y')
width = clip.get('width')
height = clip.get('height')
subImg = sheetImg.copy(int(x), int(y), int(width), int(height))
pixmap = QtGui.QPixmap.fromImage(subImg)
tile.setPixmap(pixmap)
self.addItem(tile)
I tried some stuff with connecting the TileBar's 'changed()' signal with various 'view' functions, but none of them worked. I've had a bit of trouble finding good examples of ways to use the Graphics View Framework, (most are very very small scale) so let me know if I'm doing it completely wrong.
Any help is appreciated. Thanks.
It's quite hard to tell what's wrong with your code as it's not complete and missing some parts to get it compiled. Though there are couple of places which could potentially cause the problem:
Your Title class constructor; I believe you should be calling the base class constructor there by executing: QtGui.QGraphicsPixmapItem.__init__(self, parent).
Looks like your graphic scene objects are getting constructed in the button's onclick signal. There could be problems with your signal connecting to the proper slot, you should see warnings in the output if there are such problems in your widget.
It looks like you're loading images file names from the xml file, it's quite hard to check if the logic over there is straight but potentially you could have a problem over there too.
Below is simplified version of your code which loads ab image into the Title and adds it to the graphic scene:
import sys
from PyQt4 import QtGui, QtCore
class Tile(QtGui.QGraphicsPixmapItem):
def __init__(self, parent=None):
QtGui.QGraphicsPixmapItem.__init__(self, parent)
self.idAttr = -1
class TileBar(QtGui.QGraphicsScene):
def __init__(self, parent=None):
QtGui.QGraphicsScene.__init__(self, parent)
#def loadTiles(self, filename):
def loadTiles(self):
sheetImg = QtGui.QImage("put_your_file_name_here.png")
pixmap = QtGui.QPixmap.fromImage(sheetImg)
tile = Tile()
tile.setPixmap(pixmap)
self.addItem(tile)
# skipping your ElementTree parsing logic here
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setWindowTitle('NT State Editor')
winWidth = 1024
winHeight = 768
screen = QtGui.QDesktopWidget().availableGeometry()
screenCenterX = (screen.width() - winWidth) / 2
screenCenterY = (screen.height() - winHeight) / 2
self.setGeometry(screenCenterX, screenCenterY, winWidth, winHeight)
#self.tileMap = Tiletilebar.Map()
self.tileBar = TileBar()
#mapView = QtGui.QGraphicsView(self.tileMap)
self.tileBarView = QtGui.QGraphicsView(self.tileBar)
#button = self.tilebar.LoadTilesButton()
button = QtGui.QPushButton()
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked()"),
self.tileBar.loadTiles)
#self.tileBar.loadTiles('some_file_name')
hbox = QtGui.QHBoxLayout()
#hbox.addWidget(mapView)
hbox.addWidget(self.tileBarView)
hbox.addWidget(button)
mainWidget = QtGui.QWidget()
mainWidget.setLayout(hbox)
self.setCentralWidget(mainWidget)
app = QtGui.QApplication([])
exm = MainWindow()
exm.show()
app.exec_()
hope this helps, regards

Categories