wxPython: "Super" wx.SpinCtrl with float values, layout inside sizer - python

wx.SpinCtrl is limited to spinning across integers, and not floats. Therefore, I am building a wx.TextCtrl + wx.SpinButton combo class which enables me to spin across floats. I am able to size and layout both of them programmatically so that the combo looks exactly the same as an ordinary wx.SpinCtrl.
I am subclassing this combo from the wx.TextCtrl because I want its parent panel to catch wx.EVT_TEXT events. I would appreciate if you can improve on this argument of mine.
The wx.EVT_SPIN_UP and wx.EVT_SPIN_DOWN events from the wx.SpinButton are both internal implementations and the parent frame doesn't care about these events.
Now, I just hit a brick wall. My combo class doesn't work well with sizers. After .Add()ing the combo class to a wx.GridBagSizer, only the wx.TextCtrl is laid out within the wx.GridBagSizer. The wx.SpinButton is left on its own by itself. The wx.EVT_SPIN* bindings work very well, though.
My problem is the layout. How should I write the class if I want the wx.GridBagSizer to treat it as one widget?
Here is my combo class code:
class SpinnerSuper(wx.TextCtrl):
def __init__(self, parent, max):
wx.TextCtrl.__init__(self, parent=parent, size=(48, -1))
spin = wx.SpinButton(parent=parent, style=wx.SP_VERTICAL, size=(-1, 21))
self.OnInit()
self.layout(spin)
self.internalBindings(spin)
self.SizerFlag = wx.ALIGN_CENTER
self.min = 0
self.max = max
def OnInit(self):
self.SetValue(u"0.000")
def layout(self, spin):
pos = self.GetPosition()
size = self.GetSize()
RightEdge = pos[0] + size[0]
TopEdge = pos[1] - (spin.GetSize()[1]/2 - size[1]/2)
spin.SetPosition((RightEdge, TopEdge))
def internalBindings(self, spin):
spin.Bind(wx.EVT_SPIN_UP, self.handlerSpinUp(self), spin)
spin.Bind(wx.EVT_SPIN_DOWN, self.handlerSpinDown(self), spin)
def handlerSpinUp(CallerObject, *args):
def handler(CallerObject, *data):
text = data[0]
prev = text.GetValue()
next = float(prev) + 0.008
text.SetValue("{0:0.3f}".format(next))
return lambda event: handler(CallerObject, *args)
def handlerSpinDown(CallerObject, *args):
def handler(CallerObject, *data):
text = data[0]
prev = text.GetValue()
next = float(prev) - 0.008
text.SetValue("{0:0.3f}".format(next))
return lambda event: handler(CallerObject, *args)

You need to override DoGetBestSize() if you want your control to be
correctly managed by sizers. Have a look at CreatingCustomControls.
You could also have a look at FloatSpin that ships with wxPython
(in wx.lib.agw) from version 2.8.9.2 upwards.
In response to your comments:
Implementing DoGetBestSize() does not require drawing bitmaps directly. You just need to find a way, how you can determine the best size of your new widget. Typically you'd just use
the sizes of the two widgets it is composed of (text + spinner) as basis.
To let sizers treat two widgets as one, you can place them in another sizer.
The recommended way to implement a custom widget with wxPython is to derive your new widget from wx.PyControl, add a sizer to it and add the two widgets you want to combine to that sizer.

As mentionned in Kit's comments, FloatSpin is now the way to go.
It has been integrated in recent versions.
Here is a simple example of usage:
import wx
from wx.lib.agw.floatspin import FloatSpin
class Example_FloatSpin(wx.Frame):
def __init__(self, parent, title):
super(Example_FloatSpin, self).__init__(parent, title=title, size=(480, 250))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
spin = FloatSpin(panel, value=0.0, min_val=0.0, max_val=8.0, increment=0.5, digits=2, size=(100,-1))
vbox.Add(spin, proportion=0, flag=wx.CENTER, border=15)
panel.SetSizer(vbox)
self.Centre()
self.Show()
if __name__ == '__main__':
app = wx.App()
Example_FloatSpin(None, title='Check FloatSpin')
app.MainLoop()

Related

How to save selected element from combobox as variable in PyQt5?

I'm interested in how to save a selected value from my combobox as variable, so when I press e.g. B then I want it to be saved as SelectedValueCBox = selected value, which would be B in this case.
Thank you for your help
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 - StockWindow"
self.left = 0
self.top = 0
self.width = 200
self.height = 300
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.tab_widget = MyTabWidget(self)
self.setCentralWidget(self.tab_widget)
self.show()
class MyTabWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
#self.layout = QGridLayout(self)
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tabs.resize(300, 200)
self.tabs.addTab(self.tab1, "Stock-Picker")
self.tab1.layout = QGridLayout(self)
button = QToolButton()
self.tab1.layout.addWidget(button, 1,1,1,1)
d = {'AEX':['A','B','C'], 'ATX':['D','E','F'], 'BEL20':['G','H','I'], 'BIST100':['J','K','L']}
def callback_factory(k, v):
return lambda: button.setText('{0}_{1}'.format(k, v))
menu = QMenu()
self.tab1.layout.addWidget(menu, 1,1,1,1)
for k, vals in d.items():
sub_menu = menu.addMenu(k)
for v in vals:
action = sub_menu.addAction(str(v))
action.triggered.connect(callback_factory(k, v))
button.setMenu(menu)
self.tab1.setLayout(self.tab1.layout)
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Since you're already returning a lambda for the connection, the solution is to use a function instead.
class MyTabWidget(QWidget):
def __init__(self, parent):
# ...
def callback_factory(k, v):
def func():
self.selectedValueCBox = v
button.setText('{0}_{1}'.format(k, v))
return func
# ...
self.selectedValueCBox = None
Note that your code also has many issues.
First of all, you should not add the menu to the layout: not only it doesn't make any sense (the menu should pop up, while adding it to a layout makes it "embed" into the widget, and that's not good), but it also creates graphical issues especially because you added the menu to the same grid "slot" (1, 1, 1, 1) which is already occupied by the button.
Creating a layout with a widget as argument automatically sets the layout to that widget. While in your case it doesn't create a big issue (since you've already set the layout) you should not create self.tab1.layout with self. Also, since you've already set the QVBoxLayout (due to the parent argument), there's no need to call setLayout() again.
A widget container makes sense if you're actually going to add more than one widget. You're only adding a QTabWidget to its layout, so it's almost useless, and you should just subclass from QTabWidget instead.
Calling resize on a widget that is going to be added on a layout is useless, as the layout will take care of the resizing and the previous resize call will be completely ignored. resize() makes only sense for top level widgets (windows) or the rare case of widgets not managed by a layout.
self.layout() is an existing property of all QWidgets, you should not overwrite it. The same with self.width() and self.height() you used in the App class.
App should refer to an application class, but you're using it for a QMainWindow. They are radically different types of classes.
Finally, you have no combobox in your code. A combobox is widget that is completely different from a drop down menu like the one you're using. I suggest you to be more careful with the terminology in the future, otherwise your question would result very confusing, preventing people to actually being able to help you.

wxPython: Switching between multiple panels with a button

I would like to have two (I will add more later) panels that occupy the same space within the frame and for them to be shown/hidden when the respective button is pressed on the toolbar, "mListPanel" should be the default. Currently the settings panel is shown when the application is launched and the buttons don't do anything. I've searched and tried lots of stuff for hours and still can't get it to work. I apologise if it's something simple, I've only started learning python today.
This is what the code looks like now:
import wx
class mListPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
#wx.StaticText(self, -1, label='Search:')#, pos=(10, 3))
#wx.TextCtrl(self, pos=(10, 10), size=(250, 50))
class settingsPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
class bifr(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Title")
self.listPanel = mListPanel(self)
self.optPanel = settingsPanel(self)
menuBar = wx.MenuBar()
fileButton = wx.Menu()
importItem = wx.Menu()
fileButton.AppendMenu(wx.ID_ADD, 'Add M', importItem)
importItem.Append(wx.ID_ANY, 'Import from computer')
importItem.Append(wx.ID_ANY, 'Import from the internet')
exitItem = fileButton.Append(wx.ID_EXIT, 'Exit')
menuBar.Append(fileButton, 'File')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.Quit, exitItem)
toolBar = self.CreateToolBar()
homeToolButton = toolBar.AddLabelTool(wx.ID_ANY, 'Home', wx.Bitmap('icons/home_icon&32.png'))
importLocalToolButton = toolBar.AddLabelTool(wx.ID_ANY, 'Import from computer', wx.Bitmap('icons/comp_icon&32.png'))
importToolButton = toolBar.AddLabelTool(wx.ID_ANY, 'Import from the internet', wx.Bitmap('icons/arrow_bottom_icon&32.png'))
settingsToolButton = toolBar.AddLabelTool(wx.ID_ANY, 'settings', wx.Bitmap('icons/wrench_plus_2_icon&32.png'))
toolBar.Realize()
self.Bind(wx.EVT_TOOL, self.switchPanels(), settingsToolButton)
self.Bind(wx.EVT_TOOL, self.switchPanels(), homeToolButton)
self.Layout()
def switchPanels(self):
if self.optPanel.IsShown():
self.optPanel.Hide()
self.listPanel.Show()
self.SetTitle("Home")
elif self.listPanel.IsShown():
self.listPanel.Hide()
self.optPanel.Show()
self.SetTitle("Settings")
else:
self.SetTitle("Error")
self.Layout()
def Quit(self, e):
self.Close()
if __name__ == "__main__":
app = wx.App(False)
frame = bifr()
frame.Show()
app.MainLoop()
first off, i would highly suggest that you learn about wxpython sizers and get a good understanding of them (they're really not that hard the understand) as soon as possible before delving deeper into wxpython, just a friendly tip :).
as for your example, a few things:
when your'e not using sizers, you have to give size and position for every window or else they just wont show, so you'd have to change your panel classes to something like this (again this is only for demonstration, you should be doing this with wx.sizers, and not position and size):
class mListPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent,pos=(0,100),size=(500,500))
class settingsPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent,pos=(0,200),size (1000,1000))
further more, when binding an event it should look like this:
self.Bind(wx.EVT_TOOL, self.switchPanels, settingsToolButton)
self.Bind(wx.EVT_TOOL, self.switchPanels, homeToolButton)
notice how I've written only the name of the function without the added (), as an event is passed to it, you cant enter your own parameters to a function emitted from an event (unless you do it with the following syntax lambda e:FooEventHandler(paramaters))
and the event handler (function) should look like this:
def switchPanels(self, event):
if self.optPanel.IsShown():
self.optPanel.Hide()
self.listPanel.Show()
self.SetTitle("Home")
elif self.listPanel.IsShown():
self.listPanel.Hide()
self.optPanel.Show()
self.SetTitle("Settings")
else:
self.SetTitle("Error")
self.Layout()
there should always be a second parameter next to self in functions that are bind to event as the event object is passes there, and you can find its associated methods and parameters in the documentation (in this example it is the wx.EVT_TOOL).

wxPython: disable multiple buttons

I have a wxPython GUI which looks like this:
As you can see there are three "columns", each enclosed in a wx.StaticBox. I want to disable all the buttons, text box, and radio buttons within a column. I tried using .Disable on the static box but it had no effect. Is there an easy way to disable everything within a static box?
A wx.StaticBox is not actually a container, it's just:
a rectangle drawn around other panel items to denote a logical grouping of items.
So, the only way you can do this with StaticBox is to keep track of the widgets you've logically grouped together, and call Disable on all of them.
Or, alternatively, you can put the widgets into any of the actual container widgets (like windows and sizers) instead, and then just Disable the container.
Make the StaticBoxSizer into a class attribute if you haven't already (i.e. self.mySizer instead of just mySizer). Then you can use its GetChildren() method to return the widgets. Next you just loop through the widgets and Disable them. Something like this should do it:
children = self.mySizer.GetChildren()
for child in children:
child.Disable()
You might have to add a check in the loop to make sure it's a button or a text control. I recommend using Python's isinstance for that.
Here is a working example:
"""
Demonstration on how to disable / enable all objects within a sizer
Reinhard Daemon / Austria
08.10.2019
"""
import wx
class MainWindow(wx.Frame):
def __init__(self, parent=None):
wx.Frame.__init__(self, parent, -1,
title='Disable / Enable all Widgets within a Sizer',size=(500,200))
self.Move((50,50))
panel = wx.Panel(self)
# layout (sizers, boxes,...):
top_sizer = wx.BoxSizer(wx.VERTICAL)
widget_box = wx.StaticBox(panel, id=-1,
label='Widgets, which are controlled')
widget_box.SetBackgroundColour("yellow")
control_box = wx.StaticBox(panel, -1,
label='Widgets, which controll')
control_box.SetBackgroundColour("yellow")
self.widget_sizer = wx.StaticBoxSizer(widget_box, wx.HORIZONTAL)
control_sizer = wx.StaticBoxSizer(control_box, wx.HORIZONTAL)
# create the widgets:
widget_1 = wx.TextCtrl(panel, value='Text 1')
widget_2 = wx.RadioButton(panel, label='Radio 1')
widget_3 = wx.RadioButton(panel, label='Radio 2')
widget_4 = wx.Button(panel, label='Button 1')
widget_disable = wx.Button(panel, label='DISABLE')
self.widget_enable = wx.Button(panel, label='ENABLE', pos = (100,50))
# add the widgets to the layout:
self.widget_sizer.Add(widget_1)
self.widget_sizer.Add(widget_2)
self.widget_sizer.Add(widget_3)
self.widget_sizer.Add(widget_4)
control_sizer.Add(widget_disable)
control_sizer.Add(self.widget_enable)
# finalize the layout:
top_sizer.Add(sizer=self.widget_sizer, flag=wx.CENTER | wx.EXPAND)
top_sizer.AddSpacer(30)
top_sizer.Add(control_sizer, 0, wx.CENTER | wx.EXPAND)
panel.SetSizer(top_sizer)
panel.Fit()
# bindings:
widget_disable.Bind(wx.EVT_BUTTON, self.on_button_disable)
self.widget_enable.Bind(wx.EVT_BUTTON, self.on_button_enable)
def on_button_disable(self, evt):
children = self.widget_sizer.GetChildren()
for child in children:
print(child.GetWindow(),end='')
try:
child.GetWindow().Enable(False)
print(' DISABLED')
except:
print(' ERROR')
def on_button_enable(self, evt):
children = self.widget_sizer.GetChildren()
for child in children:
print(child.GetWindow(),end='')
try:
child.GetWindow().Enable(True)
print(' ENABLED')
except:
print(' ERROR')
if __name__ == "__main__":
app = wx.App()
view1 = MainWindow()
view1.Show()
app.MainLoop()

Show another window wxpython?

I have been looking around the Internet but I am not sure if there is a way to show 2 classes in wxPython in 2 separate windows. And could we communicate between them (like one class being the dialog and the other the main class)?
I think I did this before using Show() but I am not sure how to repeat this.
So basically I would like to be able to have a dialog but by using a class instead. This would be more powerful than using Modal dialogs.
Thanks
Here you have a simple example of two frames communicating:
The trick is in sending an object reference to share between frames, either creating one inside the other (as in this case) or through a common parent.
The code is:
import wx
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, size=(150,100), title='MainFrame')
pan =wx.Panel(self)
self.txt = wx.TextCtrl(pan, -1, pos=(0,0), size=(100,20), style=wx.DEFAULT)
self.but = wx.Button(pan,-1, pos=(10,30), label='Tell child')
self.Bind(wx.EVT_BUTTON, self.onbutton, self.but)
self.child = ChildFrame(self)
self.child.Show()
def onbutton(self, evt):
text = self.txt.GetValue()
self.child.txt.write('Parent says: %s' %text)
class ChildFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, None, size=(150,100), title='ChildFrame')
self.parent = parent
pan = wx.Panel(self)
self.txt = wx.TextCtrl(pan, -1, pos=(0,0), size=(100,20), style=wx.DEFAULT)
self.but = wx.Button(pan,-1, pos=(10,30), label='Tell parent')
self.Bind(wx.EVT_BUTTON, self.onbutton, self.but)
def onbutton(self, evt):
text = self.txt.GetValue()
self.parent.txt.write('Child says: %s' %text)
if __name__ == "__main__":
App=wx.PySimpleApp()
MainFrame().Show()
App.MainLoop()
You can also use pubsub to communicate between two frames. I show one way of doing just that in this article: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/
If you don't want the first frame to hide itself, just remove the line with the Hide() in it.

Easiest way to create a scrollable area using wxPython?

Okay, so I want to display a series of windows within windows and have the whole lot scrollable. I've been hunting through the wxWidgets documentation and a load of examples from various sources on t'internet. Most of those seem to imply that a wx.ScrolledWindow should work if I just pass it a nested group of sizers(?):
The most automatic and newest way is to simply let sizers determine the scrolling area.This is now the default when you set an interior sizer into a wxScrolledWindow with wxWindow::SetSizer. The scrolling area will be set to the size requested by the sizer and the scrollbars will be assigned for each orientation according to the need for them and the scrolling increment set by wxScrolledWindow::SetScrollRate.
...but all the example's I've seen seem to use the older methods listed as ways to achieve scrolling. I've got something basic working, but as soon as you start scrolling you lose the child windows:
import wx
class MyCustomWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetSize((50,50))
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self)
dc.SetPen(wx.Pen('blue', 2))
dc.SetBrush(wx.Brush('blue'))
(width, height)=self.GetSizeTuple()
dc.DrawRoundedRectangle(0, 0,width, height, 8)
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.scrolling_window = wx.ScrolledWindow( self )
self.scrolling_window.SetScrollRate(1,1)
self.scrolling_window.EnableScrolling(True,True)
self.sizer_container = wx.BoxSizer( wx.VERTICAL )
self.sizer = wx.BoxSizer( wx.HORIZONTAL )
self.sizer_container.Add(self.sizer,1,wx.CENTER,wx.EXPAND)
self.child_windows = []
for i in range(0,50):
wind = MyCustomWindow(self.scrolling_window)
self.sizer.Add(wind, 0, wx.CENTER|wx.ALL, 5)
self.child_windows.append(wind)
self.scrolling_window.SetSizer(self.sizer_container)
def OnSize(self, event):
self.scrolling_window.SetSize(self.GetClientSize())
if __name__=='__main__':
app = wx.PySimpleApp()
f = TestFrame()
f.Show()
app.MainLoop()
Oops.. turns out I was creating my child windows badly:
wind = MyCustomWindow(self)
should be:
wind = MyCustomWindow(self.scrolling_window)
..which meant the child windows were waiting for the top-level window (the frame) to be re-drawn instead of listening to the scroll window. Changing that makes it all work wonderfully :)

Categories

Resources