Related
I am creating instances of two different objects (features_object and line_object) on a canvas. The idea is to connect several of the features by lines (). Later on when features are moved around the lines should follow.
At the moment my issue is that, when I apply the delete method on the lines I can delete them (Lines created between features by left mouse click. Line deleted by right mouse double click). However with the similar method of the feature class nothing happens! I cannot delete the features! The features seem invisible on the canvas! Is there any solution to that?
Thanks a lot!
from tkinter import Tk, Frame, Canvas, Text, END, TRUE, BOTH, CURRENT
click = 0
class line_object:
all_connections = []
def __init__(self):
self.connections_data = []
def create_line(self, master, start_elem, end_elem, tag_start, tag_end):
self.master = master
self.start_elem = start_elem
self.end_elem = end_elem
self.tag_start = tag_start
self.tag_end = tag_end
self.start_x = self.master.coords(self.start_elem)[0]
self.start_y = self.master.coords(self.start_elem)[1]
self.end_x = self.master.coords(self.end_elem)[0]
self.end_y = self.master.coords(self.end_elem)[1]
self.line_tag = (f'Connector_{self.start_elem}_{self.end_elem}', 'connection', 'drag')
self.master.delete(self.line_tag)
self.line_id = self.master.create_line(self.start_x, self.start_y, self.end_x, self.end_y, fill="red", width=6, tags=(self.line_tag, self.tag_start, self.tag_end))
self.master.tag_lower(self.line_id)
self.bind_events_lines()
def bind_events_lines(self):
self.master.bind('<Double Button-3>', self.deleteLine)
def deleteLine(self, event=None):
actual = self.master.find_withtag(CURRENT)
self.master.delete(actual)
class features_object():
def __init__(self):
self.features_data = []
def create_feature(self, master, feature_text, feature_xpos, feature_ypos, feature_color):
self.master = master
self.feature_text = feature_text
self.feature_xpos = feature_xpos
self.feature_ypos = feature_ypos
self.feature_color = feature_color
self.feature_frame = Frame(self.master, bg=self.feature_color, border=20)
self.feature_text = Text(self.feature_frame, font=("Helvetica", 12), relief='flat', width=20, height=3, selectbackground=self.feature_color, selectforeground="black", exportselection=TRUE)
self.feature_text.grid(row=0, column=0, padx=5, pady=5, sticky='w')
self.feature_text.config(wrap='word')
self.feature_text.insert(END, feature_text)
self.feature_tags = 'drag'
self.feature_id = self.master.create_window(self.feature_xpos, self.feature_ypos, window=self.feature_frame, tags=self.feature_tags)
self.master.itemconfigure(self.feature_id, tags=[self.feature_id])
self.bind_events_features()
def bind_events_features(self):
self.feature_frame.bind('<Button-1>', self.draw_line_with_bind)
self.feature_frame.bind('<Double Button-3>', self.deleteFeature)
def deleteFeature(self, event):
actual = self.master.find_withtag(CURRENT)
self.master.delete(actual)
def draw_line_with_bind(self, event):
global click, start_x, start_y, end_x, end_y, elem_start, tag_start
if click == 0:
elem_start = self.feature_id
tag_start = f'{elem_start}'
click = 1
elif click == 1:
elem_end = self.feature_id
tag_end = f'{elem_end}'
lin = line_object()
self.connection = lin.create_line(draw_canvas, elem_start, elem_end, tag_start, tag_end)
click = 0
window = Tk()
window.geometry("1000x800")
frame_start = Frame(window)
frame_start.pack(expand=TRUE, fill=BOTH)
draw_canvas = Canvas(frame_start)
draw_canvas.pack(expand=TRUE, fill=BOTH)
features_object().create_feature(draw_canvas, 'feature A', 100, 100, 'red')
features_object().create_feature(draw_canvas, 'feature B', 300, 300, 'green')
features_object().create_feature(draw_canvas, 'feature C', 500, 500, 'magenta')
def read_id(event):
currently_clicked = draw_canvas.find_withtag(CURRENT)
print(f'Currently clicked instance {currently_clicked}')
draw_canvas.bind('<Button-2>', read_id)
if __name__ == '__main__':
window.mainloop()
I am not finding any documentation showing which widgets QDataWidgetMapper actually works for and have not found any implementation of mapping with a QTableWidget.
It definitely works for QLineEdit's and QComboBoxes, which are input widgets, but is it possible to map to a QTableWidget?
Goal is to use QUndoStack to undo/redo text change in each widget when added to the QUndostack. I want to be able to undo/redo text changes for the items in the QTableWidget as well as the QLineEdits and QComboBoxes.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class CommandTextEdit(QtWidgets.QUndoCommand):
def __init__(self, window, index, oldText, newText, description):
super(CommandTextEdit,self).__init__()
self.index = index
self.window = window
self.oldText = oldText
self.newText = newText
def redo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.newText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
def undo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.oldText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
class Model(QtCore.QAbstractListModel):
itemDataChanged = QtCore.pyqtSignal(object,object, object, object)
def __init__(self, text = [], parent = None):
super(Model,self).__init__(parent)
self._text = text
def rowCount(self,parent=QtCore.QModelIndex()):
return len(self._text)
def data(self,index,role):
row = index.row()
if role == QtCore.Qt.EditRole:
return self._text[row]
if role == QtCore.Qt.DisplayRole:
value = self._text[row]
return self._text[row]
def model(self):
return self
def flags(self, index):
return QtCore.Qt.ItemIsEditable |QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role = QtCore.Qt.UserRole + 1):
if index.isValid():
if role == QtCore.Qt.EditRole:
oldValue = self.data(index,role)
self._text[index.row()] = value
self.dataChanged.emit(index, index)
if oldValue != value:
self.itemDataChanged.emit(index, oldValue, value, role)
return True
return False
class Window(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(Window,self).__init__(parent)
self.setCentralWidget(QtWidgets.QWidget(self))
self.setWindowTitle('Widget Mapping GUI')
mainlayout = QtWidgets.QVBoxLayout()
#Information for widgets
items = ["","H","N","M"]
#LineEdit1
self.labelLineEdit1 = QtWidgets.QLabel()
self.labelLineEdit1.setText('LineEdit1')
self.LineEdit1 = QtWidgets.QLineEdit()
firstBox = QtWidgets.QHBoxLayout()
firstBox.addWidget(self.labelLineEdit1)
firstBox.addWidget(self.LineEdit1)
#LineEdit2
self.labelLineEdit2 = QtWidgets.QLabel()
self.labelLineEdit2.setText('LineEdit2')
self.LineEdit2 = QtWidgets.QLineEdit()
secondBox = QtWidgets.QHBoxLayout()
secondBox.addWidget(self.labelLineEdit2)
secondBox.addWidget(self.LineEdit2)
#ComboBox1
self.labelComboBox1 = QtWidgets.QLabel()
self.labelComboBox1.setText('ComboBox1')
self.ComboBox1 = QtWidgets.QComboBox()
self.ComboBox1.addItems(items)
thirdBox = QtWidgets.QHBoxLayout()
thirdBox.addWidget(self.labelComboBox1)
thirdBox.addWidget(self.ComboBox1)
#ComboBox2
self.labelComboBox2 = QtWidgets.QLabel()
self.labelComboBox2.setText('ComboBox2')
self.ComboBox2 = QtWidgets.QComboBox()
self.ComboBox2.addItems(items)
fourthBox = QtWidgets.QHBoxLayout()
fourthBox.addWidget(self.labelComboBox2)
fourthBox.addWidget(self.ComboBox2)
#TableWidget
self.TableWidget = QtWidgets.QTableWidget(5,1)
#Set header labels
self.TableWidget.setHorizontalHeaderLabels(["Dimensions"])
self.TableWidget.setVerticalHeaderLabels(["A","B","C","D","E"])
self.TableWidget.setItem(0,1,QtWidgets.QTableWidgetItem('1'))
fifthBox = QtWidgets.QVBoxLayout()
fifthBox.addWidget(self.TableWidget)
#Add Layouts
mainlayout.addLayout(firstBox)
mainlayout.addLayout(secondBox)
mainlayout.addLayout(thirdBox)
mainlayout.addLayout(fourthBox)
mainlayout.addLayout(fifthBox)
self.centralWidget().setLayout(mainlayout)
#Model
self.mapper = None
self.model = Model(['','','','',''])
self.setModel(self.model)
#QUndoStack
self.undoStack = QtWidgets.QUndoStack()
self.stackView = QtWidgets.QUndoView(self.undoStack)
self.stackView.setWindowTitle('StackView')
self.stackView.show()
#Run init methods
self.createActions()
self.makeConnections()
self.listViewMethod()
def createActions(self):
self.UndoAct = QtWidgets.QAction("Undo", self)
self.UndoAct.setShortcut(QtGui.QKeySequence.Undo)
self.UndoAct.triggered.connect(self.undoStack.undo)
self.RedoAct = QtWidgets.QAction("Redo", self)
self.RedoAct.setShortcut(QtGui.QKeySequence.Redo)
self.RedoAct.triggered.connect(self.undoStack.redo)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(self.UndoAct)
self.toolbar.addAction(self.RedoAct)
def listViewMethod(self):
self.listView = QtWidgets.QListView()
self.listView.setModel(self.model)
self.listView.setWindowTitle('ListView')
self.listView.show()
def makeConnections(self):
self.model.itemDataChanged.connect(self.itemDataChangedSlot)
def setModel(self, model):
self.mapper = QtWidgets.QDataWidgetMapper(self)
self.mapper.setOrientation(QtCore.Qt.Vertical)
self.mapper.setModel(self.model)
self.mapper.addMapping(self.LineEdit1, 0)
self.mapper.addMapping(self.LineEdit2, 1)
self.mapper.addMapping(self.ComboBox1, 2)
self.mapper.addMapping(self.ComboBox2, 3)
self.mapper.addMapping(self.TableWidget,4)
self.mapper.toFirst()
def itemDataChangedSlot(self, index, oldValue, value, role):
if role == QtCore.Qt.EditRole:
command = CommandTextEdit(self, index, oldValue, value, "Text changed from '{0}' to '{1}'".format(oldValue, value))
self.undoStack.push(command)
def main():
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
To map the items of a QTableWidget, I used the setCellWidget method to map each cell to the model using a custom QLineEdit class.
Updated Code:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
#implemented stylesheets for QLineEdit to imitate a QTableWidgetItem
class CustomLineEdit(QtWidgets.QLineEdit):
def __init__(self):
super(CustomLineEdit,self).__init__()
self.setReadOnly(True)
self.setFrame(False)
self.setStyleSheet("QLineEdit { border: none; } \n" \
"QLineEdit::focus {background-color: #3daee9;} \n"\
"QLineEdit::focus::pressed {background-color: none;} \n"\
"QLineEdit::hover {background-color: #3daee9;}"
)
def mouseDoubleClickEvent(self,event):
self.setReadOnly(False)
self.setStyleSheet("QLineEdit { border: none; \nbackground-color: none;} \n" \
)
def focusOutEvent(self,event):
self.setReadOnly(True)
self.setStyleSheet("QLineEdit { border: none; } \n" \
"QLineEdit::focus {background-color: #3daee9;} \n"\
"QLineEdit::focus::pressed {background-color: none;} \n"\
"QLineEdit::hover {background-color: #3daee9;}"
)
class CommandTextEdit(QtWidgets.QUndoCommand):
def __init__(self, window, index, oldText, newText, description):
super(CommandTextEdit,self).__init__()
self.index = index
self.window = window
self.oldText = oldText
self.newText = newText
def redo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.newText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
def undo(self):
self.index.model().itemDataChanged.disconnect(self.window.itemDataChangedSlot)
self.index.model().setData(self.index, self.oldText, QtCore.Qt.EditRole)
self.index.model().itemDataChanged.connect(self.window.itemDataChangedSlot)
class Model(QtCore.QAbstractListModel):
itemDataChanged = QtCore.pyqtSignal(object,object, object, object)
def __init__(self, text = [], parent = None):
super(Model,self).__init__(parent)
self._text = text
def rowCount(self,parent=QtCore.QModelIndex()):
return len(self._text)
def data(self,index,role):
row = index.row()
if role == QtCore.Qt.EditRole:
return self._text[row]
if role == QtCore.Qt.DisplayRole:
value = self._text[row]
return self._text[row]
def model(self):
return self
def flags(self, index):
return QtCore.Qt.ItemIsEditable |QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role = QtCore.Qt.UserRole + 1):
if index.isValid():
if role == QtCore.Qt.EditRole:
oldValue = self.data(index,role)
self._text[index.row()] = value
self.dataChanged.emit(index, index)
if oldValue != value:
self.itemDataChanged.emit(index, oldValue, value, role)
return True
return False
class Window(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(Window,self).__init__(parent)
self.setCentralWidget(QtWidgets.QWidget(self))
self.setWindowTitle('Widget Mapping GUI')
mainlayout = QtWidgets.QVBoxLayout()
#Information for widgets
items = ["","H","N","M"]
#LineEdit1
self.labelLineEdit1 = QtWidgets.QLabel()
self.labelLineEdit1.setText('LineEdit1')
self.LineEdit1 = QtWidgets.QLineEdit()
firstBox = QtWidgets.QHBoxLayout()
firstBox.addWidget(self.labelLineEdit1)
firstBox.addWidget(self.LineEdit1)
#LineEdit2
self.labelLineEdit2 = QtWidgets.QLabel()
self.labelLineEdit2.setText('LineEdit2')
self.LineEdit2 = QtWidgets.QLineEdit()
secondBox = QtWidgets.QHBoxLayout()
secondBox.addWidget(self.labelLineEdit2)
secondBox.addWidget(self.LineEdit2)
#ComboBox1
self.labelComboBox1 = QtWidgets.QLabel()
self.labelComboBox1.setText('ComboBox1')
self.ComboBox1 = QtWidgets.QComboBox()
self.ComboBox1.addItems(items)
thirdBox = QtWidgets.QHBoxLayout()
thirdBox.addWidget(self.labelComboBox1)
thirdBox.addWidget(self.ComboBox1)
#ComboBox2
self.labelComboBox2 = QtWidgets.QLabel()
self.labelComboBox2.setText('ComboBox2')
self.ComboBox2 = QtWidgets.QComboBox()
self.ComboBox2.addItems(items)
fourthBox = QtWidgets.QHBoxLayout()
fourthBox.addWidget(self.labelComboBox2)
fourthBox.addWidget(self.ComboBox2)
#TableWidget
self.TableWidget = QtWidgets.QTableWidget(5,1)
#Set header labels
self.TableWidget.setHorizontalHeaderLabels(["Dimensions"])
self.TableWidget.setVerticalHeaderLabels(["A","B","C","D","E"])
self.TableWidget.setCellWidget(0,0,CustomLineEdit())
self.TableWidget.setCellWidget(1,0,CustomLineEdit())
self.TableWidget.setCellWidget(2,0,CustomLineEdit())
self.TableWidget.setCellWidget(3,0,CustomLineEdit())
self.TableWidget.setCellWidget(4,0,CustomLineEdit())
self.TableWidget.setItem(1,0,QtWidgets.QTableWidgetItem('1'))
fifthBox = QtWidgets.QVBoxLayout()
fifthBox.addWidget(self.TableWidget)
#Add Layouts
mainlayout.addLayout(firstBox)
mainlayout.addLayout(secondBox)
mainlayout.addLayout(thirdBox)
mainlayout.addLayout(fourthBox)
mainlayout.addLayout(fifthBox)
self.centralWidget().setLayout(mainlayout)
#Model
self.mapper = None
self.model = Model(['' for i in range(9)])
self.setModel(self.model)
#QUndoStack
self.undoStack = QtWidgets.QUndoStack()
self.stackView = QtWidgets.QUndoView(self.undoStack)
self.stackView.setWindowTitle('StackView')
self.stackView.show()
#Run init methods
self.createActions()
self.makeConnections()
self.listViewMethod()
def createActions(self):
self.UndoAct = QtWidgets.QAction("Undo", self)
self.UndoAct.setShortcut(QtGui.QKeySequence.Undo)
self.UndoAct.triggered.connect(self.undoStack.undo)
self.RedoAct = QtWidgets.QAction("Redo", self)
self.RedoAct.setShortcut(QtGui.QKeySequence.Redo)
self.RedoAct.triggered.connect(self.undoStack.redo)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(self.UndoAct)
self.toolbar.addAction(self.RedoAct)
def listViewMethod(self):
self.listView = QtWidgets.QListView()
self.listView.setModel(self.model)
self.listView.setWindowTitle('ListView')
self.listView.show()
def makeConnections(self):
self.model.itemDataChanged.connect(self.itemDataChangedSlot)
def setModel(self, model):
self.mapper = QtWidgets.QDataWidgetMapper(self)
self.mapper.setOrientation(QtCore.Qt.Vertical)
self.mapper.setModel(self.model)
self.mapper.addMapping(self.LineEdit1, 0)
self.mapper.addMapping(self.LineEdit2, 1)
self.mapper.addMapping(self.ComboBox1, 2)
self.mapper.addMapping(self.ComboBox2, 3)
self.mapper.addMapping(self.TableWidget.cellWidget(0,0), 4)
self.mapper.addMapping(self.TableWidget.cellWidget(1,0), 5)
self.mapper.addMapping(self.TableWidget.cellWidget(2,0), 6)
self.mapper.addMapping(self.TableWidget.cellWidget(3,0), 7)
self.mapper.addMapping(self.TableWidget.cellWidget(4,0), 8)
self.mapper.toFirst()
def itemDataChangedSlot(self, index, oldValue, value, role):
if role == QtCore.Qt.EditRole:
command = CommandTextEdit(self, index, oldValue, value, "Text changed from '{0}' to '{1}'".format(oldValue, value))
self.undoStack.push(command)
def main():
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I am making a program that gives you a list of artists to choose from and when you click on the artist it opens a new window and gives you a selection of their paintings. However, when I try to do this nothing happens on the new window. I can't put any buttons on it and even static text doesn't work on it, it works just fine on the parent window, but not the child window. Am I missing something or do I need to do something else completely? Here's my code:
import webbrowser
import sqlite3
import wx
conn = sqlite3.connect("dbPaintings.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS tblPaintings(Artist TEXT, PaintingName TEXT, Link TEXT)")
path = 'Artists Paintings.txt'
def insertingPaintings():
line = ''
filePaintings=open(path,'r')
for x in range(15):
arrPaintings = filePaintings.readline().split(",")
if len(arrPaintings) == 3:
strArtist = arrPaintings[0]
strPainting = arrPaintings[1]
strLink = arrPaintings[2]
strLink = strLink.split("\\")[0]
c.execute("INSERT INTO tblPaintings(Artist, PaintingName, Link) VALUES(:ArtistName, :Painting, :Url)", {'ArtistName':strArtist,'Painting':strPainting,'Url':strLink})
conn.commit()
#insertingPaintings()
class ArtFrame(wx.Frame):
def __init__(self, keyID, title, parent):
wx.Frame.__init__(self,parent=parent,title=title,size=(800,600))
panel = wx.Panel(self)
wx.StaticText(panel,-1,"Working",(566,345))
self.SetBackgroundColour('white')
if keyID=='Auguste Renoir':
self.AugusteRenoirWork()
def AugusteRenoirWork(self):
UmbrellasButtonImage = wx.Image('The Umbrellas.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
UmbrellasButton = wx.BitmapButton(wx.Panel(self),-1,UmbrellasButtonImage,pos=(200,200),size=(200,250))
class MainFrame(wx.Frame):
def __init__(self,*args,**kwargs):
super(MainFrame, self).__init__(*args, **kwargs, size=(1280,720), style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX)
self.basicGUI()
self.Centre()
def basicGUI(self):
panel = wx.Panel(self)
self.SetBackgroundColour('black')
self.SetTitle('French Impressionism')
font=wx.Font(18, wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
AugusteRenoirButtonImage = wx.Image('Auguste Renoir.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
AugusteRenoirText = wx.StaticText(panel,-1,"Auguste Renoir",(237,345))
AugusteRenoirText.SetForegroundColour("#e6b800")
AugusteRenoirText.SetFont(font)
AugusteRenoirButton = wx.BitmapButton(panel,-1,AugusteRenoirButtonImage,pos=(220,85),size=(200,250))
self.Bind(wx.EVT_BUTTON,self.RenoirWindow,AugusteRenoirButton)
ClaudeMonetButtonImage = wx.Image('Claude Monet.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
ClaudeMonetText = wx.StaticText(panel,-1,"Claude Monet",(566,345))
ClaudeMonetText.SetForegroundColour("#206020")
ClaudeMonetText.SetFont(font)
ClaudeMonetButton = wx.BitmapButton(panel,-1,ClaudeMonetButtonImage,pos=(540,85),size=(200,250))
self.Bind(wx.EVT_BUTTON,self.MonetWindow,ClaudeMonetButton)
VincentVanGoghButtonImage = wx.Image('Vincent Van Gogh.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
VincentVanGoghText = wx.StaticText(panel,-1,"Vincent Van Gogh",(862,345))
VincentVanGoghText.SetForegroundColour("#3385ff")
VincentVanGoghText.SetFont(font)
VincentVanGoghButton = wx.BitmapButton(panel,-1,VincentVanGoghButtonImage,pos=(860,85),size=(200,250))
self.Bind(wx.EVT_BUTTON,self.VanGoghWindow,VincentVanGoghButton)
GeorgesSeuratButtonImage = wx.Image('Georges Seurat.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
GeorgesSeuratText = wx.StaticText(panel,-1,"Georges Seurat",(393,640))
GeorgesSeuratText.SetForegroundColour("#990099")
GeorgesSeuratText.SetFont(font)
GeorgesSeuratButton = wx.BitmapButton(panel,-1,GeorgesSeuratButtonImage,pos=(380,380),size=(200,250))
self.Bind(wx.EVT_BUTTON,self.SeuratWindow,GeorgesSeuratButton)
PaulCezanneButtonImage = wx.Image('Paul Cezanne.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
PaulCezanneText = wx.StaticText(panel,-1,"Paul Cezanne",(735,640))
PaulCezanneText.SetForegroundColour("#cc2900")
PaulCezanneText.SetFont(font)
PaulCezanneButton = wx.BitmapButton(panel,-1,PaulCezanneButtonImage,pos=(710,380),size=(200,250))
self.Bind(wx.EVT_BUTTON,self.CezanneWindow,PaulCezanneButton)
self.Show(True)
def RenoirWindow(self,event):
wx.Panel(self)
title = "Auguste Renoir's Works"
keyID='Auguste Renoir'
frame = ArtFrame(parent=wx.GetTopLevelParent(self),title=title,keyID=keyID)
frame.Show(True)
def MonetWindow(self,event):
wx.Panel(self)
title = "Claude Monet's Works"
keyID='Claude Monet'
frame = ArtFrame(parent=wx.GetTopLevelParent(self),title=title,keyID=keyID)
def VanGoghWindow(self,event):
wx.Panel(self)
title = "Vincent Van Gogh's Works"
keyID='Vincent Van Gogh'
frame = ArtFrame(parent=wx.GetTopLevelParent(self),title=title,keyID=keyID)
def SeuratWindow(self,event):
wx.Panel(self)
title = "Georges Seurat's Works"
keyID='Georges Seurat'
frame = ArtFrame(parent=wx.GetTopLevelParent(self),title=title,keyID=keyID)
def CezanneWindow(self,event):
wx.Panel(self)
title = "Paul Cezanne's Works"
keyID='Paul Cezanne'
frame = ArtFrame(parent=wx.GetTopLevelParent(self),title=title,keyID=keyID)
app = wx.App()
MainFrame(None)
app.MainLoop()
Please note it would be easier if you posted a smaller snippet of code that can be run by anyone without the need of your database and jpg's etc
In
class ArtFrame(wx.Frame):
def __init__(self, keyID, title, parent):
wx.Frame.__init__(self,parent=parent,title=title,size=(800,600))
panel = wx.Panel(self)
wx.StaticText(panel,-1,"Working",(566,345))
self.SetBackgroundColour('white')
if keyID=='Auguste Renoir':
self.AugusteRenoirWork()
def AugusteRenoirWork(self):
UmbrellasButtonImage = wx.Image('The Umbrellas.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
UmbrellasButton = wx.BitmapButton(wx.Panel(self),-1,UmbrellasButtonImage,pos=(200,200),size=(200,250))
when the wx.BitmapButton is created it has a new panel as its parent wx.Panel(self), instead use the panel that was created in the init
something like this
class ArtFrame(wx.Frame):
def __init__(self, keyID, title, parent):
wx.Frame.__init__(self,parent=parent,title=title,size=(800,600))
self.panel = wx.Panel(self)
wx.StaticText(self.panel,-1,"Working",(566,345))
self.SetBackgroundColour('white')
if keyID=='Auguste Renoir':
self.AugusteRenoirWork()
def AugusteRenoirWork(self):
UmbrellasButtonImage = wx.Image('The Umbrellas.jpg',wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
UmbrellasButton = wx.BitmapButton(self.panel,-1,UmbrellasButtonImage,pos=(200,200),size=(200,250))
guys am trying to write a program that takes details from one window and imports them onto a profile of another window.. i want it be on the same app... all i see is qdialog class and I dont wanna use it
am taking data from the first window to import it to the second window
here's my code of the first
def loader(self):
widget = QWidget()
self.setCentralWidget(widget)
#layouts
self.layout = QFormLayout()
self.descriLayout = QVBoxLayout()
self.buttonLayout = QHBoxLayout()
#QFormLayout dealz
self.name = QLabel('name')
items = ['male' , 'female' , 'none']
self.sexchooser = QComboBox()
for item in items:
self.sexchooser.addItem(item)
self.age = QLabel('age')
self.optcourse = QLabel('Opted Course')
self.nameEdit = QLineEdit()
#self.nameEdit.editingFinished()
self.nameEdit.setPlaceholderText('enter name here')
self.coursEdit = QLineEdit()
self.coursEdit.setPlaceholderText('Mt || Ph || St')
self.sexLabel = QLabel('sex')
#age selector
self.ageSelector = QComboBox()
for x in range(18 , 40):
self.ageSelector.addItem(str(x))
self.descriptor = QPlainTextEdit()
self.descriptor.setPlaceholderText('describe yourself here')
self.descriptor.setUndoRedoEnabled(True)
self.layout.addRow(self.name , self.nameEdit)
self.layout.addRow(self.optcourse , self.coursEdit)
self.layout.addRow(QLabel('sex') , self.sexchooser)
self.layout.addRow(QLabel('Age') , self.ageSelector)
#buttons dealz
self.SubmitButton = QPushButton('&Submit')
self.SubmitButton.clicked.connect(self.detailer)
self.cancelButton = QPushButton("Can&cel")
self.cancelButton.clicked.connect(self.close)
self.buttonLayout.addWidget(self.SubmitButton)
self.buttonLayout.addWidget(self.cancelButton)
self.descriLayout.addLayout(self.layout)
self.descriLayout.addWidget(self.descriptor)
self.descriLayout.addLayout(self.buttonLayout)
self.show()
widget.setLayout(self.descriLayout)
self.setMinimumSize(300 , 350)
self.setMaximumSize(300 , 350)
self.setWindowTitle('DETAILS')
def detailer(self):
#the second window called here
thanks in advance
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.loader()
def loader(self):
widget = QWidget()
self.setCentralWidget(widget)
#layouts
self.layout = QFormLayout()
self.descriLayout = QVBoxLayout()
self.buttonLayout = QHBoxLayout()
#QFormLayout dealz
self.name = QLabel('name')
items = ['male' , 'female' , 'none']
self.sexchooser = QComboBox()
for item in items:
self.sexchooser.addItem(item)
self.age = QLabel('age')
self.optcourse = QLabel('Opted Course')
self.nameEdit = QLineEdit()
#self.nameEdit.editingFinished()
self.nameEdit.setPlaceholderText('enter name here')
self.coursEdit = QLineEdit()
self.coursEdit.setPlaceholderText('Mt || Ph || St')
self.sexLabel = QLabel('sex')
#age selector
self.ageSelector = QComboBox()
for x in range(18 , 40):
self.ageSelector.addItem(str(x))
self.descriptor = QPlainTextEdit()
self.descriptor.setPlaceholderText('describe yourself here')
self.descriptor.setUndoRedoEnabled(True)
self.layout.addRow(self.name , self.nameEdit)
self.layout.addRow(self.optcourse , self.coursEdit)
self.layout.addRow(QLabel('sex') , self.sexchooser)
self.layout.addRow(QLabel('Age') , self.ageSelector)
#buttons dealz
self.SubmitButton = QPushButton('&Submit')
self.SubmitButton.clicked.connect(self.detailer)
self.cancelButton = QPushButton("Can&cel")
self.cancelButton.clicked.connect(self.close)
self.buttonLayout.addWidget(self.SubmitButton)
self.buttonLayout.addWidget(self.cancelButton)
self.descriLayout.addLayout(self.layout)
self.descriLayout.addWidget(self.descriptor)
self.descriLayout.addLayout(self.buttonLayout)
self.show()
widget.setLayout(self.descriLayout)
self.setMinimumSize(300 , 350)
self.setMaximumSize(300 , 350)
self.setWindowTitle('DETAILS')
def detailer(self):
print("#the second window called here")
self.statusBar().showMessage("Switched to window 2")
valueText = " {} \n {} \n {} \n {} \n {}"\
.format(self.nameEdit.text(),
self.coursEdit.text(),
self.sexchooser.currentText(),
self.ageSelector.currentText(),
self.descriptor.toPlainText())
self.cams = Window2(valueText, self)
self.cams.show()
class Window2(QDialog):
def __init__(self, value, parent=None):
super().__init__(parent)
self.setGeometry(750, 100, 300, 350)
self.parent = parent
self.setWindowTitle('Window2')
self.setWindowIcon(self.style().standardIcon(QStyle.SP_FileDialogInfoView))
label1 = QLabel(value)
self.button = QPushButton()
self.button.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
self.button.setIcon(self.style().standardIcon(QStyle.SP_ArrowLeft))
self.button.setIconSize(QSize(200, 200))
layoutV = QVBoxLayout()
self.pushButton = QPushButton(self)
self.pushButton.setStyleSheet('background-color: rgb(0,0,255); color: #fff')
self.pushButton.setText('Click me!')
self.pushButton.clicked.connect(self.goMainWindow)
layoutV.addWidget(self.pushButton)
layoutH = QHBoxLayout()
layoutH.addWidget(label1)
layoutH.addWidget(self.button)
layoutV.addLayout(layoutH)
self.setLayout(layoutV)
def goMainWindow(self):
self.parent.show()
self.close()
if __name__=='__main__':
app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
sys.exit(app.exec_())
i have a page containing two tabs.i want to add a fadeIn effect when i change the tabs.Is that possible?
import sys
from PyQt4.QtCore import QTimeLine
from PyQt4.QtGui import *
class FaderWidget(QWidget):
def __init__(self, old_widget, new_widget):
QWidget.__init__(self, new_widget)
self.old_pixmap = QPixmap(new_widget.size())
old_widget.render(self.old_pixmap)
self.pixmap_opacity = 1.0
self.timeline = QTimeLine()
self.timeline.valueChanged.connect(self.animate)
self.timeline.finished.connect(self.close)
self.timeline.setDuration(333)
self.timeline.start()
self.resize(new_widget.size())
self.show()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
painter.setOpacity(self.pixmap_opacity)
painter.drawPixmap(0, 0, self.old_pixmap)
painter.end()
def animate(self, value):
self.pixmap_opacity = 1.0 - value
self.repaint()
class StackedWidget(QStackedWidget):
def __init__(self, parent = None):
QStackedWidget.__init__(self, parent)
def setCurrentIndex(self, index):
self.fader_widget = FaderWidget(self.currentWidget(), self.widget(index))
QStackedWidget.setCurrentIndex(self, index)
def setPage1(self):
self.setCurrentIndex(0)
def setPage2(self):
self.setCurrentIndex(1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QWidget()
stack = StackedWidget()
stack.addWidget(QCalendarWidget())
editor = QTextEdit()
editor.setPlainText("Hello world! "*100)
stack.addWidget(editor)
page1Button = QPushButton("Page 1")
page2Button = QPushButton("Page 2")
page1Button.clicked.connect(stack.setPage1)
page2Button.clicked.connect(stack.setPage2)
layout = QGridLayout(window)
layout.addWidget(stack, 0, 0, 1, 2)
layout.addWidget(page1Button, 1, 0)
layout.addWidget(page2Button, 1, 1)
window.show()
sys.exit(app.exec_())
this is code that shows some fade effect but i m getting nothing from it and how it works and how to implement on tabs. it will be really appreciable if someone could help me implement it on tabs as well.
thanks in advance.
With the same logic as the code you show, each widget will be placed inside a QStackedWidget, where one of them will be the widget that will be displayed and the other will be the FaderWidget.
class FaderWidget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.pixmap_opacity = None
self.timeline = QTimeLine(333, self)
self.timeline.valueChanged.connect(self.animate)
self.timeline.finished.connect(self.close)
def start(self, old_widget, new_widget):
self.pixmap_opacity = 1.0
self.old_pixmap = QPixmap(new_widget.size())
old_widget.render(self.old_pixmap)
self.timeline.start()
self.resize(new_widget.size())
self.show()
def paintEvent(self, event):
if self.pixmap_opacity:
QWidget.paintEvent(self, event)
painter = QPainter(self)
painter.setOpacity(self.pixmap_opacity)
painter.drawPixmap(0, 0, self.old_pixmap)
def animate(self, value):
self.pixmap_opacity = 1.0 - value
self.update()
class FaderTabWidget(QTabWidget):
def __init__(self, parent=None):
QTabWidget.__init__(self, parent)
self.currentChanged.connect(self.onCurrentIndex)
self.last = -1
self.current = self.currentIndex()
def onCurrentIndex(self, index):
self.last = self.current
self.current = self.currentIndex()
if self.widget(self.last):
self.widget(self.last).setCurrentIndex(1)
old_widget = self.widget(self.last).widget(0)
current_widget = self.widget(self.current).widget(0)
fade = self.widget(self.current).widget(1)
fade.start(old_widget, current_widget)
def addTab(self, widget, text):
stack = QStackedWidget(self)
stack.addWidget(widget)
fade = FaderWidget(self)
fade.timeline.finished.connect(lambda: stack.setCurrentIndex(0))
stack.addWidget(fade)
stack.setCurrentIndex(0 if self.currentIndex() == -1 else 1)
QTabWidget.addTab(self, stack, text)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = QWidget()
tabWidget = FaderTabWidget()
tabWidget.addTab(QCalendarWidget(), "Tab1")
editor = QTextEdit()
editor.setPlainText("Hello world! " * 100)
tabWidget.addTab(editor, "Tab2")
layout = QVBoxLayout(window)
layout.addWidget(tabWidget)
window.show()
sys.exit(app.exec_())