wxPython - Widgets on top of each other with GridSizer - grid-layout

I'm learning wxPython and experimenting with GridSizer as it's my favourite way of handling layouts.
Besides religiously reading the API for the classes I'm using, I scavenged bits and pieces around the wx wiki and tutorials to wrap everything together.
Somehow though, the widgets I'm testing, two ListBoxes which are supposed to be on top of each other, appear on top of each other instead.
I can only see the first ListBox once I click: the elements pop up as I select them and TABbing goes back to the first list.
There is clearly something I'm inadvertenly skipping. Looking around I thought the problem was that I wasn't using Layout() correctly, but I tested it with all containers to no avail. Also, the issues I found around the web seem to mention resizing to refresh the window, but even by resizing my window nothing of value happens.
Finally, here's the code:
import wx
class MainWindow(wx.Frame):
def __init__(self):
super().__init__(parent=None, id=-1,
title="Test Window",
style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
main_panel = wx.Panel(parent=self, id=wx.ID_ANY)
wx.ListBox(main_panel, id=wx.ID_ANY, size=wx.Size(200, 200),
style=wx.LB_SINGLE | wx.LB_ALWAYS_SB | wx.LB_SORT,
choices=[
"Babble",
"Bobble",
"Bubble"
])
wx.ListBox(main_panel, id=wx.ID_ANY, size=wx.Size(200, 200),
style=wx.LB_SINGLE | wx.LB_ALWAYS_SB,
choices=[
"One",
"Two",
"Three"
])
main_grid = wx.GridSizer(cols=1, rows=2, gap=wx.Size(50, 50))
main_grid.Add(main_panel)
self.SetAutoLayout(True)
self.SetSizer(main_grid)
self.Layout()
self.Show(True)
if __name__ == "__main__":
app = wx.App(False)
app.SetTopWindow(MainWindow())
app.MainLoop()

Give the individual items names and Add them to the sizer, not the entire panel.
import wx
class MainWindow(wx.Frame):
def __init__(self):
super().__init__(parent=None, id=-1,
title="Test Window",
style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
main_panel = wx.Panel(parent=self, id=wx.ID_ANY, size=(400,600))
list1 = wx.ListBox(main_panel, id=wx.ID_ANY, size=wx.Size(200, 200),
style=wx.LB_SINGLE | wx.LB_ALWAYS_SB | wx.LB_SORT,
choices=[
"Babble",
"Bobble",
"Bubble"
])
list2 = wx.ListBox(main_panel, id=wx.ID_ANY, size=wx.Size(200, 200),
style=wx.LB_SINGLE | wx.LB_ALWAYS_SB,
choices=[
"One",
"Two",
"Three"
])
main_grid = wx.GridSizer(cols=1, gap=(50,50))
main_grid.Add(list1)
main_grid.Add(list2)
self.SetAutoLayout(True)
self.SetSizer(main_grid)
self.Layout()
self.Show(True)
if __name__ == "__main__":
app = wx.App(False)
app.SetTopWindow(MainWindow())
app.MainLoop()

Related

Extending selection in either direction in a QTextEdit

Currently, QTextEdit permits selecting text and then altering that selection with shift-click-drag only on the side of the selection opposite the anchor. The anchor is placed where the selection started. If the user tries to alter the selection near the start, the selection pivots around the anchor point instead of extending. I'd like to permit changing the selection from either side.
My first attempt is to simply set the anchor on the opposite side from where the cursor is located. Say, for example, the selection is from 10 to 20. If the cursor is shift-click-dragged at position 8, then the anchor would be set to 20. If the cursor is shift-click-dragged at position 22, then the anchor would be set to 10. Later, I'll try something more robust, perhaps based on the center point of the selection.
I thought this code would work, but it does not seem to affect the default behavior at all. What have I missed?
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class TextEditor(QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setReadOnly(True)
self.setMouseTracking(True)
def mouseMoveEvent(self, event):
point = QPoint()
x = event.x() #these are relative to the upper left corner of the text edit window
y = event.y()
point.setX(x)
point.setY(y)
self.mousepos = self.cursorForPosition(point).position() # get character position of current mouse using local window coordinates
if event.buttons()==Qt.LeftButton:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
start = -1 #initialize to something impossible
end = -1
cursor = self.textCursor()
select_point1 = cursor.selectionStart()
select_point2 = cursor.selectionEnd()
if select_point1 < select_point2: # determine order of selection points
start = select_point1
end = select_point2
elif select_point2 < select_point1:
start = select_point2
end = select_point1
if self.mousepos > end: # if past end when shift-click then trying to extend right
cursor.setPosition(start, mode=QTextCursor.MoveAnchor)
elif self.mousepos < start: # if before start when shift-click then trying to extend left
cursor.setPosition(end, mode=QTextCursor.MoveAnchor)
if start != -1 and end != -1: #if selection exists then this should trigger
self.setTextCursor(cursor)
super().mouseMoveEvent(event)
Here's a first stab at implementing shift+click extension of the current selection. It seems to work okay, but I have not tested it to death, so there may be one or two glitches. The intended behaviour is that a shift+click above or below the selection should extend the whole selection in that direction; and a shift+click with drag should do the same thing, only continuously.
Note that I have also set the text-interaction flags so that the caret is visible in read-only mode, and the selection can also be manipulated with the keyboard in various ways (e.g. ctrl+shift+right extends the selection to the next word).
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class TextEditor(QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setReadOnly(True)
self.setTextInteractionFlags(
Qt.TextSelectableByMouse |
Qt.TextSelectableByKeyboard)
def mouseMoveEvent(self, event):
if not self.setShiftSelection(event, True):
super().mouseMoveEvent(event)
def mousePressEvent(self, event):
if not self.setShiftSelection(event):
super().mousePressEvent(event)
def setShiftSelection(self, event, moving=False):
if (event.buttons() == Qt.LeftButton and
QApplication.keyboardModifiers() == Qt.ShiftModifier):
cursor = self.textCursor()
start = cursor.selectionStart()
end = cursor.selectionEnd()
if not moving or start != end:
anchor = cursor.anchor()
pos = self.cursorForPosition(event.pos()).position()
if pos <= start:
start = pos
elif pos >= end:
end = pos
elif anchor == start:
end = pos
else:
start = pos
if pos <= anchor:
start, end = end, start
cursor.setPosition(start, QTextCursor.MoveAnchor)
cursor.setPosition(end, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
return True
return False
if __name__ == '__main__':
app = QApplication(sys.argv)
window = TextEditor()
window.setText(open(__file__).read())
window.setGeometry(600, 50, 800, 800)
window.show()
sys.exit(app.exec_())

Sudden additional scroll bar for wx.grid.Grid

I use wx.grid.Grid for display table.
The number of grid rows is changed and it may be more than 2000.
For number of rows less than 1723 GUI displays normally.
But if I have greater than or equal to 1723 rows, GUI displays incorrectly:
Sudden additional vertical scroll bar appears.
If aim a mouse cursor on this additional scrollbar then my laptop display blinks
wx.grid.Grid don't expands into ScrolledPanel.
How can I use wx.grid.Grid with greate number of rows (more than 2000)?
Thanks in advance.
Code Sample:
import wx
import wx.grid
from wx.lib.scrolledpanel import ScrolledPanel
class TestPanel(ScrolledPanel):
def __init__(self, parent):
ScrolledPanel.__init__(self, parent, wx.ID_ANY, size=(640, 480))
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self._create_table(), 1, wx.EXPAND | wx.ALL, 5)
self.SetSizer(self.sizer)
self.SetupScrolling()
self.SetAutoLayout(1)
def _create_table(self):
_table = wx.grid.Grid(self, -1)
_table.CreateGrid(0, 1)
for i in xrange(1723): # Work normally If I use 1722 rows
_table.AppendRows()
_table.SetCellValue(i, 0, str(i))
return _table
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
title="Scroll table", size=(640, 480))
self.fSizer = wx.BoxSizer(wx.VERTICAL)
self.fSizer.Add(TestPanel(self), 1, wx.EXPAND)
self.SetSizer(self.fSizer)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame = TestFrame()
app.MainLoop()
In this case you should use a wx.Panel instead of the ScrolledPanel. The grid is able to manage its scrolling on its own, it doesn't need to have any help from its parent.
If you have other widgets to display that wont fit in the panel, and you want to be able to scroll them and the grid in and out of view, then using the ScrolledPanel would be appropriate, but then you should do something to constrain the size of the grid so it doesn't try to expand to show all cells.

DIV tag equivalent in Qt Graphics Framework

I am working on a simple desktop application where I have to show a tree structure of folders and files along with other diagrams. For this I chose Qt and python (PySide). I need a structure like below (Forgive me for the bad drawing. But you get the idea):
The folders can be double clicked to expand/shrink. When a folder expands, new child elements need to take more space, and the folders below the current folder must move down. Similarly when the folder is shrunk, the folders below the current folder must come up; just like a standard folder system.
Hence I am in search of a <div> equivalent element in Qt where I can place each directory and all of its children inside that div and the div can expand and shrink. This way I don't have to write code for a re-draw every time the folder is opened/closed. Currently I have to calculate each item's position and place the child items respective to that position. That is a lot of calculation and no of items are > 1000. With a div, I will just re-calculate positions of child items and resize the div. Other divs can then automatically re-draw themselves.
I am not using QTreeView because as I said earlier, I have to draw other diagrams and connect these folders with them. QTreeView will live in its own space (with scroll bar and stuff), and I won't be able to draw lines to connect items in QTreeView and QGraphicsScene.
You can view my current work here in github. Here is the file that has my work.
I'm not sure what you're thinking of "<div>". It's just the most simple HTML container, and it seems to have nothing to do with your goal.
You can use graphics layouts to align items in the scene automatically. Here's how it can be implemented:
from PySide import QtGui, QtCore
class Leaf(QtGui.QGraphicsProxyWidget):
def __init__(self, path, folder = None):
QtGui.QGraphicsProxyWidget.__init__(self)
self.folder = folder
label = QtGui.QLabel()
label.setText(QtCore.QFileInfo(path).fileName())
self.setWidget(label)
self.setToolTip(path)
self.setAcceptedMouseButtons(QtCore.Qt.LeftButton)
def mousePressEvent(self, event):
if self.folder:
self.folder.toggleChildren()
class Folder(QtGui.QGraphicsWidget):
def __init__(self, path, isTopLevel = False):
QtGui.QGraphicsWidget.__init__(self)
self.offset = 32
childrenLayout = QtGui.QGraphicsLinearLayout(QtCore.Qt.Vertical)
childrenLayout.setContentsMargins(self.offset, 0, 0, 0)
flags = QtCore.QDir.AllEntries | QtCore.QDir.NoDotAndDotDot
for info in QtCore.QDir(path).entryInfoList(flags):
if info.isDir():
childrenLayout.addItem(Folder(info.filePath()))
else:
childrenLayout.addItem(Leaf(info.filePath()))
self.childrenWidget = QtGui.QGraphicsWidget()
self.childrenWidget.setLayout(childrenLayout)
mainLayout = QtGui.QGraphicsLinearLayout(QtCore.Qt.Vertical)
mainLayout.setContentsMargins(0, 0, 0, 0)
self.leaf = Leaf(path, self)
mainLayout.addItem(self.leaf)
mainLayout.addItem(self.childrenWidget)
if isTopLevel:
mainLayout.addStretch()
self.setLayout(mainLayout)
def paint(self, painter, option, widget):
QtGui.QGraphicsWidget.paint(self, painter, option, widget)
if self.childrenWidget.isVisible() and self.childrenWidget.layout().count() > 0:
lastChild = self.childrenWidget.layout().itemAt(self.childrenWidget.layout().count() - 1)
lastChildY = self.childrenWidget.geometry().top() + \
lastChild.geometry().top() + self.leaf.geometry().height() / 2;
painter.drawLine(self.offset / 2, self.leaf.geometry().bottom(), self.offset / 2, lastChildY)
for i in range(0, self.childrenWidget.layout().count()):
child = self.childrenWidget.layout().itemAt(i)
childY = self.childrenWidget.geometry().top() + \
child.geometry().top() + self.leaf.geometry().height() / 2
painter.drawLine(self.offset / 2, childY, self.offset, childY)
def toggleChildren(self):
if self.childrenWidget.isVisible():
self.layout().removeItem(self.childrenWidget)
self.childrenWidget.hide()
self.leaf.widget().setStyleSheet("QLabel { color : blue; }")
print "hide"
else:
self.childrenWidget.show()
self.layout().insertItem(1, self.childrenWidget)
self.leaf.widget().setStyleSheet("")
self.update()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
scene = QtGui.QGraphicsScene()
view = QtGui.QGraphicsView(scene)
# put your root path here
scene.addItem(Folder("/usr/share/alsa", True))
view.show()
view.resize(400, 400)
sys.exit(app.exec_())

wxPython Solitaire GUI

I'm writing a Solitaire GUI using wxPython, and I'm on Windows 7. I've only written one GUI before (in Java Swing), so I'm not as familiar as I could be with all the different types of widgets and controls. I'm faced with the challenge of having resizable, cascading piles of cards in the Tableaux of the Solitaire board. To me, using BitmapButtons for each card (or at least for face-up cards) and having a panel contain a pile of cards seemed natural, since it is legal to move sub-piles of cards in the Tableau from pile to pile in Solitaire. I'm sure there is a better way to do this, but for now I've been fiddling with a smaller GUI (not my main GUI) to try and achieve this. I've attached the code for the test GUI below.
Note: My main GUI uses a GridBagSizer with 14 cells. I haven't tried using the following panel/buttons in the GridBagSizer, or even know if a GridBagSizer is the best way to go about this.
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id_, title):
wx.Frame.__init__(self, parent, id_, title, size=(810, 580))
self.panel = wx.Panel(self, size=(72, 320), pos=(20,155))
self.buttons = []
self.init_buttons()
def init_buttons(self):
for i in range(6):
face_down = wx.Image('img/cardback.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
wid = face_down.GetWidth()
hgt = face_down.GetHeight()
bmpbtn = wx.BitmapButton(self.panel, -1, bitmap=face_down, pos=(20,155+7*i), size=(wid, hgt))
bmpbtn.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
self.buttons.append(bmpbtn)
for i in range(1,14):
rank = 14 - i
if i % 2 == 0:
filename = 'img/%sC.png' % rank
else:
filename = 'img/%sH.png' % rank
img = wx.Image(filename, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
wid = img.GetWidth()
hgt = img.GetHeight()
bmpbtn = wx.BitmapButton(self.panel, -1, bitmap=img, pos=(20, 177+20*i), size=(wid, hgt))
bmpbtn.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
self.buttons.append(bmpbtn)
def onMouseOver(self, event):
#event.Skip()
pass
class MyApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.frame = MyFrame(None, -1, "Solitaire")
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True
app = MyApp(0)
app.MainLoop()
This is what results from running:
http://oi44.tinypic.com/1zv4swj.jpg
Which I was satisfied with, until I moved my mouse over some of the buttons:
http://oi44.tinypic.com/2rdupmq.jpg
This must have to do with the EVT_ENTER_WINDOW event. I attempted to write an event handler, but realized I didn't really know how to achieve what I need. According to the docs, a BitmapButton has different bitmaps for each of its states - hover, focus, selected, inactive, etc. However, I do not want to change the Bitmap on a mouseover event. I simply want the button to stay put, and to not display itself on top of other buttons.
Any help would be greatly appreciated. Incidentally, if anybody has advice for a better way (than GridBagSizer and these panels of buttons) to implement this GUI, I would love that!
I would recommend against using actual window controls for each of the cards. I would instead have a single canvas upon which you render the card bitmaps in their appropriate locations. You'll have to do a little extra math to determine what cards are being clicked on, but this is definitely the way to go.
Use a wx.Panel with a EVT_PAINT handler to do your drawing.
Here's a starting point that is written to use double-buffering to avoid flickering.
P.S. You can use bitmap = wx.Bitmap(path) to load an image, instead of bothering with wx.Image and converting it to a bitmap object.
import wx
class Panel(wx.Panel):
def __init__(self, parent):
super(Panel, self).__init__(parent)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.Bind(wx.EVT_PAINT, self.on_paint)
self.Bind(wx.EVT_LEFT_DOWN, self.on_left_down)
self.Bind(wx.EVT_LEFT_UP, self.on_left_up)
def on_left_down(self, event):
print 'on_left_down', event.GetPosition()
def on_left_up(self, event):
print 'on_left_up', event.GetPosition()
def on_paint(self, event):
dc = wx.AutoBufferedPaintDC(self)
# Use dc.DrawBitmap(bitmap, x, y) to draw the cards here
class Frame(wx.Frame):
def __init__(self):
super(Frame, self).__init__(None)
self.SetTitle('My Title')
Panel(self)
def main():
app = wx.App()
frame = Frame()
frame.Center()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()

Turning WA_TranslucentBackground off stops window repainting

I have a PyQt4.9 window where I would like to toggle the translucency on or off. The reason being is that it sometimes shows a full size phonon video control which doesn't work when the WA_TranslucentBackground attribute is set. (Due to a Qt bug https://bugreports.qt.io/browse/QTBUG-8119)
The problem I have is, after I turn WA_TranslucentBackground attribute back to false, after it has been true, the Window will no longer redraw, so it remains stuck showing the same thing from that point on. Interestingly, click events still respond.
Some example code follows. Click the increment button, and it will update the button text. Click the toggle button and then click the increment button again, and updates no longer show. Clicking the exit button closes the window, showing the events are still responding.
If anyone has any solutions, workarounds or fixes I'd appreciate them. Thanks.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Settings(QWidget):
def __init__(self, desktop):
QWidget.__init__(self)
self.setAttribute(Qt.WA_TranslucentBackground, True)
self.setWindowFlags(Qt.FramelessWindowHint)
self.istransparent = True
self.count = 0
self.setWindowTitle("Transparent")
self.resize(300, 150)
self.incr_button = QPushButton("Increment")
toggle_button = QPushButton("Toggle Transparency")
exit_button = QPushButton("Exit")
grid = QGridLayout()
grid.addWidget(self.incr_button, 0, 0)
grid.addWidget(toggle_button, 1, 0)
grid.addWidget(exit_button, 2, 0)
self.setLayout(grid)
self.connect(toggle_button, SIGNAL("clicked()"), self.toggle)
self.connect(self.incr_button, SIGNAL("clicked()"), self.increment)
self.connect(exit_button, SIGNAL("clicked()"), self.close)
def increment(self):
self.count = self.count + 1
self.incr_button.setText("Increment (%i)" % self.count)
def toggle(self):
self.istransparent = not self.istransparent
self.setAttribute(Qt.WA_TranslucentBackground, self.istransparent)
if __name__ == "__main__":
app = QApplication(sys.argv)
s = Settings(app.desktop())
s.show()
sys.exit(app.exec_())
Try to replace self.setAttribute(Qt.WA_TranslucentBackground, ...) calls in __init__ and toggle with following method.
def set_transparency(self, enabled):
if enabled:
self.setAutoFillBackground(False)
else:
self.setAttribute(Qt.WA_NoSystemBackground, False)
self.setAttribute(Qt.WA_TranslucentBackground, enabled)
self.repaint()
Tested on PyQt-Py2.7-x86-gpl-4.9-1 (Windows 7)

Resources