wxpython SetStatusText on StatusBar doesn't work - python

I'm training on wxpython by making a window with a menu bar and a status bar.
I'm on mac os so maybe that it works differently because I don't know what is the problem with my code, but I didn't find anything on the Internet.
Here is my code :
#!/usr/bin/python
# coding: utf-8
import wx
class Menus(wx.Frame):
def __init__(self, ptitle):
wx.Frame.__init__(self, None, 1, title = ptitle, size = (500, 300))
menuFile = wx.Menu()
menuFile.Append(wx.ID_OPEN, "&Open\tCTRL+o")
menuFile.Append(wx.ID_CLOSE, "&Close\tCTRL+c")
menuFile.AppendSeparator()
menuFile.Append(wx.ID_EXIT, "&Quit\tCTRL+q")
menuBar = wx.MenuBar()
menuBar.Append(menuFile, "&File")
self.SetMenuBar(menuBar)
self.bar = wx.StatusBar(self, 1)
self.bar.SetFieldsCount(2)
self.bar.SetStatusWidths([1,1])
self.SetStatusBar(self.bar)
self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
self.Bind(wx.EVT_MENU, self.OnOpen, id=wx.ID_OPEN)
self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_CLOSE)
def OnOpen(self, evt):
self.bar.SetStatusText("Choice -> open", 1)
def OnClose(self, evt):
self.bar.SetStatusText("Choice -> close", 1)
def OnExit(self, evt):
self.Destroy()
class App(wx.App):
def OnInit(self):
window = Menus("Window with menu")
window.Show(True)
self.SetTopWindow(window)
return True
app = App()
app.MainLoop()
When I click on Open or Close, there is no text on the status bar, but there is the status bar. If I choose instead of setting the status text to print something in the terminal, it works fine. I also tried tu write self.bar.SetStatusText("Text") and it doesn't work neither.
It would be great if someone knows where is the problem with this status bar.
Thank you

With self.bar.SetStatusWidths([1,1]) you are setting the widths to 1 pixel and 1 pixel wide respectively.
You should use [-1,-1] (equal), [-1,-2] (part 2 twice as large as part 1) etc
or use fixed widths [150,200] for example.
There are two types of fields: fixed widths and variable width fields. For the fixed width fields you should specify their (constant) width in pixels. For the variable width fields, specify a negative number which indicates how the field should expand: the space left for all variable width fields is divided between them according to the absolute value of this number. A variable width field with width of -2 gets twice as much of it as a field with width -1 and so on.
For example, to create one fixed width field of width 100 in the right part of the status bar and two more fields which get 66% and 33% of the remaining space correspondingly, you should use an array containing -2, -1 and 100.
The "Close current document" message, I suspect, is internal, very much like the automatic icon added to the menu.
Finally, self.bar.SetStatusText("Text") should read self.bar.SetStatusText("Text",1) where the 1 is the index of the status bar field that you want the text to be displayed in.
e.g.
self.bar = wx.StatusBar(self, 1)
self.bar.SetFieldsCount(3)
self.bar.SetStatusWidths([200,-1,-2])
self.SetStatusBar(self.bar)
self.bar.SetStatusText("Second position",1)
self.bar.SetStatusText("Third position",2)

Related

PyQt6 auto-resize QTextEdit to fit content problem

I have a bunch of QTextEdits in a QVBoxLayout in a QScrollArea.
The texts can often get very long and the horizontal space is limited by design, and QTextEdit automatically wraps text in multiple lines which is good.
I want to automatically resize the QTextEdit to fit to the wrapped text, the text itself will always be in one line, and the wrapped text can have multiple lines, I want the QTextEdits to fit to the height of wrapped lines.
By hours upon hours of Google searching, I have found a solution, but it doesn't work as expected, there can sometimes be one extra line at the bottom, I will post example code below:
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
font = QFont('Noto Serif', 9)
class Editor(QTextEdit):
doubleClicked = pyqtSignal(QTextEdit)
def __init__(self):
super().__init__()
self.setReadOnly(True)
self.setFont(font)
self.textChanged.connect(self.autoResize)
self.margins = self.contentsMargins()
self.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen)
#pyqtSlot(QMouseEvent)
def mouseDoubleClickEvent(self, e: QMouseEvent) -> None:
self.doubleClicked.emit(self)
def autoResize(self):
self.show()
height = int(self.document().size().height() + self.margins.top() + self.margins.bottom())
self.setFixedHeight(height)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.resize(405, 720)
frame = self.frameGeometry()
center = self.screen().availableGeometry().center()
frame.moveCenter(center)
self.move(frame.topLeft())
self.centralwidget = QWidget(self)
self.vbox = QVBoxLayout(self.centralwidget)
self.scrollArea = QScrollArea(self.centralwidget)
self.scrollArea.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget()
self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
self.vbox.addWidget(self.scrollArea)
self.setCentralWidget(self.centralwidget)
def addItems():
items = [
"L'Estro Armonico No. 9 in D Major\u2014III. Allegro",
"L'Estro Armonico No. 6 in A Minor\u2014III. Presto",
"L'Estro Armonico No. 6 in A Minor\u2014I. Allegro",
"L'Estro Armonico No. 1 in D major\u2014I. Allegro",
"12 Concertos Op.3 \u2014 L'estro Armonico \u2014 Concerto No. 6 In A Minor For Solo Violin RV 356\u2014Presto",
"Ultimate Mozart\u2014 The Essential Masterpieces",
"Serenade in G K.525 Eine kleine Nachtmusik\u20141. Allegro",
"Vivaldi\u2014 L'estro Armonico",
"Academy of St. Martin in the Fields",
"Are You With Me \u2014 Reality"
]
for i in items:
textbox = Editor()
textbox.setText(i)
window.verticalLayout.addWidget(textbox)
app = QApplication([])
window = Window()
window.show()
addItems()
app.exec()
Note you will need Noto Serif for it to run correctly (and of course you can just replace it), and of course you need PyQt6.
In the example, the first seven textboxs all have one extra empty line at the bottom, and the last three don't have it.
What caused the extra line and how to remove it?
Update:
I have to set Qt.WidgetAttribute.WA_DontShowOnScreen because if I don't set it, calling .show() of QTextEdit will cause the QTextEdit show up in the middle of the screen and quickly disappear, and it's annoying.
I have to call .show() because calling document().size() without show(), the values will all be 0 and I don't know why it is like this.
The problem comes from the fact that you're trying to set the height too early. In fact, if you add a print(self.show()) just after show(), you'll see that all will show a default size (probably, 256x192).
This depends on two aspects:
when a widget is shown the first time, it's not yet completely "mapped" in the OS window management, so it will use default sizes depending on many aspects;
you're setting the text before adding it to the layout, so the QTextEdit will know nothing about the required size of the parent;
Then another problem arises: if the window is resized, the contents will not adapt until the text is changed.
In order to properly set a vertical height based on the contents, you should set the document's textWidth, and also call autoResize everytime the widget is resized.
class Editor(QTextEdit):
def __init__(self):
super().__init__()
self.setReadOnly(True)
self.setFont(font)
self.textChanged.connect(self.autoResize)
def autoResize(self):
self.document().setTextWidth(self.viewport().width())
margins = self.contentsMargins()
height = int(self.document().size().height() + margins.top() + margins.bottom())
self.setFixedHeight(height)
def resizeEvent(self, event):
self.autoResize()
Note that:
the margins should be dynamically accessed, not stored in the __init__;
mouseDoubleClickEvent is a function that is called on a mouse event, it's not (nor it should) be a slot, so using the pyqtSlot decorator is pointless;
while conceptually fine for a "main" layout like in the case of a layout for the scroll area contents, setting the alignment of a layout doesn't set the alignment of its items, but only that of the layout; while the result is often the same, in practice it's very different (so the result is not always the same, especially if more layouts are added to the same parent layout);
double click in text fields is very commonly used for advanced selection (usually, select the word under the cursor), and choosing to prevent such action (thus changing a known UI convention) should be taken into careful consideration;

wx.ComboCtrl with wx.ListCtrl highlight background and sizing

I am building a wx.ComboCtrl with a wx.ListCtrl attached. The reason for doing this is because I want to set the foreground colour of the choices (the colour shows the user the status of the item). I want these colours to show when the box is dropped down and when a user has made a selection.
The problem I run into is that on Linux (Ubuntu 20.04), after a selection was made, the background colour of the wx.ComboCtrl remains blue (and the foreground colour remains white), even if I move focus to another widget. It doesn't matter which colour I set for the text to be displayed on the ComboCtrl, it remains white text with a blue background. See screenshot.
I can only get it to show me the default (gray) background with my selected foreground colour if I move the focus to another window and then back to my own window.
In Windows this doesn't happen: after selecting an item, the background colour of the ComboCtrl is default (gray), however it does show a little dotted line around the selection. See screenshot.
Here is the modified demo code that I am using to reproduce the issue. The comments in the code are left overs from some of the things I tried.
#!/usr/bin/env python
import wx
import os
#----------------------------------------------------------------------
#----------------------------------------------------------------------
# This class is used to provide an interface between a ComboCtrl and the
# ListCtrl that is used as the popoup for the combo widget.
class ListCtrlComboPopup(wx.ComboPopup):
def __init__(self):
wx.ComboPopup.__init__(self)
self.lc = None
def AddItem(self, txt, _colour):
self.lc.InsertItem(self.lc.GetItemCount(), txt)
_entry = self.lc.GetItem(self.lc.GetItemCount() - 1)
_entry.SetTextColour(_colour)
#_entry.SetItemTextColour(_colour)
self.lc.SetItem(_entry)
def OnMotion(self, evt):
item, flags = self.lc.HitTest(evt.GetPosition())
if item >= 0:
self.lc.Select(item)
self.curitem = item
def OnLeftDown(self, evt):
self.value = self.curitem
self.Dismiss()
# The following methods are those that are overridable from the
# ComboPopup base class. Most of them are not required, but all
# are shown here for demonstration purposes.
# This is called immediately after construction finishes. You can
# use self.GetCombo if needed to get to the ComboCtrl instance.
def Init(self):
self.value = -1
self.curitem = -1
# Create the popup child control. Return true for success.
def Create(self, parent):
self.lc = wx.ListCtrl(parent, style=wx.LC_SINGLE_SEL | wx.SIMPLE_BORDER | wx.LC_REPORT | wx.LC_NO_HEADER)
self.lc.InsertColumn(0, '')
self.lc.Bind(wx.EVT_MOTION, self.OnMotion)
self.lc.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
return True
# Return the widget that is to be used for the popup
def GetControl(self):
return self.lc
# Called just prior to displaying the popup, you can use it to
# 'select' the current item.
def SetStringValue(self, val):
idx = self.lc.FindItem(-1, val)
if idx != wx.NOT_FOUND:
self.lc.Select(idx)
# Return a string representation of the current item.
def GetStringValue(self):
if self.value >= 0:
return self.lc.GetItemText(self.value)
return ""
# Called immediately after the popup is shown
def OnPopup(self):
wx.ComboPopup.OnPopup(self)
# Called when popup is dismissed
def OnDismiss(self):
print (self.GetStringValue())
wx.ComboPopup.OnDismiss(self)
# This is called to custom paint in the combo control itself
# (ie. not the popup). Default implementation draws value as
# string.
def PaintComboControl(self, dc, rect):
wx.ComboPopup.PaintComboControl(self, dc, rect)
# Receives key events from the parent ComboCtrl. Events not
# handled should be skipped, as usual.
def OnComboKeyEvent(self, event):
wx.ComboPopup.OnComboKeyEvent(self, event)
# Implement if you need to support special action when user
# double-clicks on the parent wxComboCtrl.
def OnComboDoubleClick(self):
wx.ComboPopup.OnComboDoubleClick(self)
# Return final size of popup. Called on every popup, just prior to OnPopup.
# minWidth = preferred minimum width for window
# prefHeight = preferred height. Only applies if > 0,
# maxHeight = max height for window, as limited by screen size
# and should only be rounded down, if necessary.
def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
return wx.ComboPopup.GetAdjustedSize(self, minWidth, prefHeight, maxHeight)
# Return true if you want delay the call to Create until the popup
# is shown for the first time. It is more efficient, but note that
# it is often more convenient to have the control created
# immediately.
# Default returns false.
def LazyCreate(self):
return wx.ComboPopup.LazyCreate(self)
#----------------------------------------------------------------------
class MyTestPanel(wx.Panel):
def __init__(self, parent, log):
self.log = log
wx.Panel.__init__(self, parent, -1)
txt = wx.TextCtrl(self, wx.ID_ANY, pos=(100,100))
comboCtrl = wx.ComboCtrl(self, wx.ID_ANY, "Third item", (10,10), size=(200,-1), style=wx.CB_READONLY)
popupCtrl = ListCtrlComboPopup()
# It is important to call SetPopupControl() as soon as possible
comboCtrl.SetPopupControl(popupCtrl)
# Populate using wx.ListView methods
popupCtrl.AddItem("First Item", [255, 127, 0])
popupCtrl.AddItem("Second Item", [192, 127, 45])
popupCtrl.AddItem("Third Item", [25, 223, 172])
#popupCtrl.GetAdjustedSize(100, 35, 100)
#comboCtrl.SetTextColour(_colour)
comboCtrl.SetForegroundColour(wx.Colour(235, 55, 55))
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = MyTestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """<html><body>
<h2><center>wx.combo.ComboCtrl</center></h2>
A combo control is a generic combobox that allows a totally custom
popup. In addition it has other customization features. For instance,
position and size of the dropdown button can be changed.
</body></html>
"""
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
Question 1:
How can I make it so that once an item has been selected the appropriate text colour (the one I programmatically set) and default (gray) background colour is shown.
Question 2:
When dropping down the ComboCtrl, it is showing the ListCtrl, which has a single column only. You can see that the "Second item" on the list is not displayed entirely because the column is too narrow. How can I make it so that the column is always the same width as the widget itself, even when the ComboCtrl resizes (as a result of resizing the parent window)?
Question 3:
Not overly important, but while we are on the subject: is there a way to get rid of the little dotted box that is shown around the selected item when running this in Windows?
In advance, thank you very much for your thoughts and ideas on this.
Marc.

How to word wrap the header contents of QTableWidget in PyQt5 Python

I am working on PyQt5 where I have a QTableWidget. It has a header column which I want to word wrap. Below is how the table looks like:
As we can see that the header label like Maximum Variation Coefficient has 3 words, thus its taking too much column width. How can wrap the words in the header.
Below is the code:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
# Main Window
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 - QTableWidget'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createTable()
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.setLayout(self.layout)
# Show window
self.show()
# Create table
def createTable(self):
self.tableWidget = QTableWidget()
# Row count
self.tableWidget.setRowCount(3)
# Column count
self.tableWidget.setColumnCount(2)
self.tableWidget.setHorizontalHeaderLabels(["Maximum Variation Coefficient", "Maximum Variation Coefficient"])
self.tableWidget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.tableWidget.setItem(0, 0, QTableWidgetItem("3.44"))
self.tableWidget.setItem(0, 1, QTableWidgetItem("5.3"))
self.tableWidget.setItem(1, 0, QTableWidgetItem("4.6"))
self.tableWidget.setItem(1, 1, QTableWidgetItem("1.2"))
self.tableWidget.setItem(2, 0, QTableWidgetItem("2.2"))
self.tableWidget.setItem(2, 1, QTableWidgetItem("4.4"))
# Table will fit the screen horizontally
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.horizontalHeader().setSectionResizeMode(
QHeaderView.Stretch)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
I tried adding this self.tableWidget.setWordWrap(True) but this doesnt make any change. Can anyone give some good solution. Please help. Thanks
EDIT:
Also tried this :
self.tableWidget.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignHCenter | Qt.Alignment(QtCore.Qt.TextWordWrap))
But it didnt worked
In order to achieve what you need, you must set your own header and proceed with the following two assumptions:
the header must provide the correct size hint height according to the section contents in case the width of the column is not sufficient;
the text alignment must include the QtCore.Qt.TextWordWrap flag, so that the painter knows that it can wrap text;
Do note that, while the second aspect might be enough in some situations (as headers are normally tall enough to fit at least two lines), the first point is mandatory as the text might require more vertical space, otherwise some text would be cut out.
The first point requires to subclass QHeaderView and reimplement sectionSizeFromContents():
class WrapHeader(QtWidgets.QHeaderView):
def sectionSizeFromContents(self, logicalIndex):
# get the size returned by the default implementation
size = super().sectionSizeFromContents(logicalIndex)
if self.model():
if size.width() > self.sectionSize(logicalIndex):
text = self.model().headerData(logicalIndex,
self.orientation(), QtCore.Qt.DisplayRole)
if not text:
return size
# in case the display role is numeric (for example, when header
# labels are not defined yet), convert it to a string;
text = str(text)
option = QtWidgets.QStyleOptionHeader()
self.initStyleOption(option)
alignment = self.model().headerData(logicalIndex,
self.orientation(), QtCore.Qt.TextAlignmentRole)
if alignment is None:
alignment = option.textAlignment
# get the default style margin for header text and create a
# possible rectangle using the current section size, then use
# QFontMetrics to get the required rectangle for the wrapped text
margin = self.style().pixelMetric(
QtWidgets.QStyle.PM_HeaderMargin, option, self)
maxWidth = self.sectionSize(logicalIndex) - margin * 2
rect = option.fontMetrics.boundingRect(
QtCore.QRect(0, 0, maxWidth, 10000),
alignment | QtCore.Qt.TextWordWrap,
text)
# add vertical margins to the resulting height
height = rect.height() + margin * 2
if height >= size.height():
# if the height is bigger than the one provided by the base
# implementation, return a new size based on the text rect
return QtCore.QSize(rect.width(), height)
return size
class App(QWidget):
# ...
def createTable(self):
self.tableWidget = QTableWidget()
self.tableWidget.setHorizontalHeader(
WrapHeader(QtCore.Qt.Horizontal, self.tableWidget))
# ...
Then, to set the word wrap flag, there are two options:
set the alignment flag on the underlying model with setHeaderData() for each existing column:
# ...
model = self.tableWidget.model()
default = self.tableWidget.horizontalHeader().defaultAlignment()
default |= QtCore.Qt.TextWordWrap
for col in range(self.tableWidget.columnCount()):
alignment = model.headerData(
col, QtCore.Qt.Horizontal, QtCore.Qt.TextAlignmentRole)
if alignment:
alignment |= QtCore.Qt.TextWordWrap
else:
alignment = default
model.setHeaderData(
col, QtCore.Qt.Horizontal, alignment, QtCore.Qt.TextAlignmentRole)
Use a QProxyStyle to override the painting of the header, by applying the flag on the option:
# ...
class ProxyStyle(QtWidgets.QProxyStyle):
def drawControl(self, control, option, painter, widget=None):
if control in (self.CE_Header, self.CE_HeaderLabel):
option.textAlignment |= QtCore.Qt.TextWordWrap
super().drawControl(control, option, painter, widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle(ProxyStyle())
ex = App()
sys.exit(app.exec_())
Finally, consider that:
using setSectionResizeMode with ResizeToContents or Stretch, along with setStretchLastSection, will always cause the table trying to use as much space as required by the headers upon showing the first time;
by default, QHeaderView sections are not clickable (which is a mandatory requirement for sorting) and the highlightSections property is also False; both QTableView and QTableWidget create their headers with those values as True, so when a new header is set you must explicitly change those aspects if sorting and highlighting are required:
self.tableWidget.setHorizontalHeader(
WrapHeader(QtCore.Qt.Horizontal, self.tableWidget))
self.tableWidget.horizontalHeader().setSectionsClickable(True)
self.tableWidget.horizontalHeader().setHighlightSections(True)
both sorting and section highlighting can create some issues, as the sort indicator requires further horizontal space and highlighted sections are normally shown with a bold font (but are shown normally while the mouse is pressed); all this might create some flickering and odd behavior; unfortunately, there's no obvious solution for these problems, but when using the QProxyStyle it's possible to avoid some flickering by overriding the font style:
def drawControl(self, control, option, painter, widget=None):
if control in (self.CE_Header, self.CE_HeaderLabel):
option.textAlignment |= QtCore.Qt.TextWordWrap
if option.state & self.State_Sunken:
option.state |= self.State_On
super().drawControl(control, option, painter, widget)

Python/WXWidgets: ST_NO_AUTORESIZE not being honored for wx.StaticText

I want to throw up a view in the center of the screen at a fixed size, with some static text being displayed centered both horizontally and vertically.
So far, I have the following code:
import wx
class DisplayText(wx.Dialog):
def __init__(self, parent, text="", displayMode=0):
# Initialize dialog
wx.Dialog.__init__(self, parent, size=(480,320), style=( wx.DIALOG_EX_METAL | wx.STAY_ON_TOP ) )
# Center form
self.Center()
self.txtField = wx.StaticText(self, label=text, pos=(80,120), size=(320,200), style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ST_NO_AUTORESIZE)
self.txtField.SetFont(wx.Font(24, wx.DEFAULT, wx.BOLD, 0))
app = wx.App(False)
c = DisplayText(None, text="Now is the time for all good men to come to the aid of their country.")
c.Show()
app.MainLoop()
The goal is to actually have the text vertically centered, but for now, I was just trying to be explicit about the positioning of the static text on the frame.
For a brief split second, the text appears in the position I put it in, but then it quickly jumps to the very top bound of the window and expands to the maximum width. (I deliberately set the width and position low so I'd be able to see if this behavior was occurring or not.)
It does not matter if I use wx.Dialog or wx.Frame.
As you can see I did define the NO_AUTORESIZE flag, but this is not being honored.
Can anyone explain what's happening?
Python 2.7.5/wxWidgets 2.8.12.1/Mac OS X 10.8.4
Turns out that it's a limitation of Mac OS X's native dialog implementation.
The following made it work on OS X. I never did try it on Windows but from other forum posts it appears it would have worked as-is on Windows.
import wx
class DisplayText(wx.Dialog):
def __init__(self, parent, text="", displayMode=0):
# Initialize dialog
wx.Dialog.__init__(self, parent, size=(480,320), style=( wx.DIALOG_EX_METAL | wx.STAY_ON_TOP ) )
# Center form
self.Center()
# (For Mac) Setup a panel
self.panel = wx.Panel(self)
# Create text field
self.txtField = wx.StaticText(self.panel, label=text, pos=(80,120), size=(320,200), style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ST_NO_AUTORESIZE)
self.txtField.SetFont(wx.Font(24, wx.DEFAULT, wx.BOLD, 0))
self.txtField.SetAutoLayout(False)
app = wx.App(False)
c = DisplayText(None, text="Now is the time for all good men to come to the aid of their country.")
c.Show()
app.MainLoop()

How to layout wxPython panels that expand both directions

I'm building a UI in wxPython,[note 1] and I have three main body panels, two toolbars, and a status bar, with two BoxSizer elements (a vertical one containing all of the above, and a horizontal one containing the body panels). I cannot get the layout to work quite right, and I'm getting some behavior that I can't find in the documentation. I'm leaving out some details, but here is the relevant (working) part of the app:
import wx
import wx.adv
class MyApp(wx.App):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def OnInit(self):
self.frame = AppFrame(parent=None, title="My Sweet App")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
class AppFrame(wx.Frame):
def __init__(self, size=(1024, 768), *args, **kwargs):
super().__init__(size=size, *args, **kwargs)
# Menu (quit only)
menubar = wx.MenuBar()
file_menu = wx.Menu()
quit_item = wx.MenuItem(
file_menu, wx.ID_EXIT, '&Exit', 'Close the application')
file_menu.Append(quit_item)
self.Bind(wx.EVT_MENU, OnQuit, id=wx.ID_EXIT)
menubar.Append(file_menu, '&File')
self.SetMenuBar(menubar)
# Outer box wrapper
main_box = wx.BoxSizer(orient=wx.VERTICAL)
self.SetSizer(main_box)
main_box.SetMinSize(size)
# Inner box with the three main view panels in it
wrap_panels_box = wx.BoxSizer(orient=wx.HORIZONTAL)
wrap_panels_box.SetMinSize(200, 200)
panel1 = wx.Panel(self, -1)
panel2 = wx.Panel(self, -1)
panel3 = wx.Panel(self, -1)
common_flags = wx.SizerFlags().Expand().Border(wx.ALL, 5)
wrap_panels_box.AddMany([(panel1, common_flags),
(panel2, common_flags),
(panel3, common_flags)])
# Two toolbars for different sets of commands
toolbar1 = wx.ToolBar(parent=self)
tool1 = toolbar1.CreateTool(
toolId=wx.ID_NEW, label='',
bmpNormal=wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR))
toolbar1.AddTool(tool1)
toolbar1.Realize()
toolbar2 = wx.ToolBar(parent=self)
tool2 = toolbar2.CreateTool(
toolId=wx.ID_SAVE, label='',
bmpNormal=wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR))
toolbar2.AddTool(tool2)
toolbar2.Realize()
statusbar = wx.StatusBar(parent=self)
# Add all layout elements
bar_flags = common_flags.Proportion(0)
main_box.Add(toolbar1, bar_flags)
main_box.Add(wrap_panels_box, common_flags.Proportion(1))
main_box.Add(toolbar2, bar_flags)
main_box.Add(statusbar, bar_flags)
self.Layout()
def OnQuit(event):
exit(0)
if __name__ == '__main__':
app = MyApp()
app.MainLoop()
All the sub-component generation methods (_GenerateMenu(), _GenerateToolStatusBars(), and _GenerateViewPanels()) work as expected and basically as desired, so I'm leaving them aside.
The various pieces are largely in the right places, but I have a couple quirks here.
1. Status bar expansion
The status bar returned by the _GenerateToolStatusBars() method acts like it has Proportion(1) set on it: it expands or contracts vertically as the main window is expanded vertically. It also has additional space above it. I can make this stop, however, by setting the panel proportions as follows:
bar_flags = common_flags.Proportion(-1)
main_box.Add(toolbar1, bar_flags)
main_box.Add(wrap_panels_box, common_flags.Proportion(0))
main_box.Add(toolbar2, bar_flags)
main_box.Add(statusbar, bar_flags)
A -1 value isn't even documented for the Proportion()[note 2] setting on a Sizer, and the behavior basically matches what I would expect from the original code sample. What's going on here?
2. Later elements in BoxSizer sliding over earlier elements
Regardless of how I have the proportions set (at least between the two options above), the latter items behave as expected with relation to each other. They slide over the first element if the box becomes small, however. So, if I have _GenerateViewPanels() return the panels (as usual), they slide up and cover the top toolbar. If I make that do nothing (none of the normal panels are generated), the next toolbar slides up and covers the top toolbar. To reiterate: none of the bottom toolbars or panels interact with each other that way; they only do it with the first toolbar. As before, I'm confused: what's going on here?
[Edit: Made the above code a fully working sample application.]
Notes:
I'm using a wxPython snapshot build of Phoenix, specifically 2.9.5.81-r73784, running against Python 3.3 on both Windows 7 and OS X. It is possible this is a problem from the snapshot build, but I'm doubtful.
Proportion() is a fancy wrapper for the basic proportion=<value> argument for adding an element to a Sizer. As for why I tried -1, I just mis-remembered the default/base values for the proportion argument to BoxSizer.Add().
The problem is apparently with the distinct Proportion() calls. A little testing and use of the wxPython Widget Inspection Tool makes clear that common_flags is being modified by the calls on it.
All methods of SizerFlags objects return the same object (not a copy of the object), so calling a method updates the object and all references to it – it does not return a copy, but the same object. So, the original code with comments added explaining what went wrong:
common_flags = wx.SizerFlags().Expand().Border(wx.ALL, 1) # creates the object
bar_flags = common_flags.Proportion(0) # bar_flags points to the common_flags object
# Referencing common_flags with Proportion set to 0
main_box.Add(toolbar1, bar_flags)
# Changes the value of common_flags.
main_box.Add(wrap_panels_box, common_flags.Proportion(1))
# Since bar_flags points to common_flags, it also has Proportion set to 1
main_box.Add(toolbar2, bar_flags)
main_box.Add(statusbar, bar_flags)
The solution is simple: declare bar_flags and box_flags as separate objects. This involves some small repetition of code, but it's worth note that you are not repeating the action on the same object; you are performing the same actions on multiple objects. Supplying the following code instead solves the issue:
bar_flags = wx.SizerFlags().Expand().Border(wx.ALL, 1).Proportion(0)
box_flags = wx.SizerFlags().Expand().Border(wx.ALL, 1).Proportion(1)
main_box.Add(tool_status_bars.main, bar_flags)
main_box.Add(wrap_panels_box, box_flags)
main_box.Add(tool_status_bars.panel_view, bar_flags)
main_box.Add(tool_status_bars.status, bar_flags)
As expected, the boxes now relate to each other as they should: the wrap_panels_box expands, while the tool and status bars do not.

Categories

Resources