Showing plots if checkbox is checked, on python (with PyQt4) - python

I'm brand new to Python and I'm trying to make my first program with PyQt4. My problem is basically the following: I have two checkboxes (Plot1 and Plot2), and a "End" push button, inside my class. When I press End, I would like to see only the plots that the user checks, using matplotlib. I'm not being able to do that. My first idea was:
self.endButton.clicked.connect(self.PlotandEnd)
self.plot1Checkbox.clicked.connect(self.Plot1)
self.plot2Checkbox.clicked.conncet(self.Plot2)
def PlotandEnd(self)
plot1=self.Plot1()
pyplot.show(plot1)
plot2=self.Plot2()
pyplot.show(plot2)
def Plot1(self)
plot1=pyplot.pie([1,2,5,3,2])
return plot1
def Plot2(self)
plot2=pyplot.plot([5,3,5,8,2])
return plot2
This doesn't work, of course, because "PlotandEnd" will plot both figures, regardless of the respective checkbox. How can I do what I'm trying to?

Wrap the plot creation in an if statement that looks at the state of the check boxes. For example:
def PlotandEnd(self)
if self.plot1Checkbox.isChecked():
plot1=self.Plot1()
pyplot.show(plot1)
if self.plot2Checkbox.isChecked():
plot2=self.Plot2()
pyplot.show(plot2)
You also don't need the following lines:
self.plot1Checkbox.clicked.connect(self.Plot1)
self.plot2Checkbox.clicked.conncet(self.Plot2)
This does nothing useful at the moment! Qt never uses the return value of your PlotX() methods, and you only want things to happen when you click the End button, not when you click a checkbox. The PlotX() methods are only currently useful for your PlotandEnd() method.

Related

How to have multiple widget buttons perform different actions in Jupyter Notebook?

I am trying to make a series of buttons that take samples from a data set based on some scenario. I have a 3x2 group of buttons, each describing a different scenario. I can't seem to get them to perform their separate actions.
I think I understand how to connect the action of clicking a button to its response. However, I don't understand how to do the same for multiple buttons.
Here's my code that worked to get a single, standalone button to work:
button = widgets.Button(description='Generate message!')
out = widgets.Output()
def on_button_clicked(_):
samp_text = raw_data.sample(1).column(1)
# "linking function with output"
with out:
# what happens when we press the button
print(samp_text)
# linking button and function together using a button's method
button.on_click(on_button_clicked)
# displaying button and its output together
widgets.VBox([button,out])
Now what I'm trying to do is take different kinds of samples given various situations. So I have functions written for each type of sampling method that returns a table of proportions:
1 47.739362
2 44.680851
3 4.920213
9 2.659574
Name: vote, dtype: float64
However the same method in the first example with just one button doesn't work the same with multiple. How do I use widgets.Output() and how do I connect it so that clicking the button outputs the corresponding sample summary?
I expect for a clicked button to output its sample summary as shown above.
I didn't have any problem extending your example to use
multiple buttons. I don't know where you were confused.
Sometimes exceptions that occur in widget callbacks do not
get printed -- maybe you had a bug in your code that you couldn't
see for that reason. It's best to have everything
wrapped in a "with out:"
Created two buttons using the list. Guess code itself explains better.
from ipywidgets import Button, HBox
thisandthat = ['ON', 'OFF']
switch = [Button(description=name) for name in thisandthat]
combined = HBox([items for items in switch])
def upon_clicked(btn):
print(f'The circuit is {btn.description}.', end='\x1b\r')
for n in range(len(thisandthat)):
switch[n].style.button_color = 'gray'
btn.style.button_color = 'pink'
for n in range(len(thisandthat)):
switch[n].on_click(upon_clicked)
display(combined)

Change value of bokeh slider

I'd like to be able to change things about the slider (the value, the start/end values) programmatically.
So I take the standard slider.py demo, and just add this at the end:
for i in range(5):
amp_slider.value = amp_slider.value + 1
time.sleep(1)
That should move the value upwards every second for a few seconds. But the slider doesn't move. What am I doing wrong? Or similarly if I try to change the .end or .start value.
[I know sliders are supposed to be INPUT not OUTPUT devices. But nonetheless I'm trying to control its behavior.]
bokeh show() outputs the chart as html & javascript. Once it has done this it can no longer be modified (unless you wrote some javascript which was included to modify the page).
You need a library that renders in a 'dynamic' window (such as matplotlib to be able to replot a chart like this.
The only code inside your program that will be used again once the page is created is in the callback functions. If you adjust sliders.py so it reads:
def update_title(attrname, old, new):
amplitude.value += 1
Every time you update the text, the amplitude will increase.

Identifying Left and Right Mouse Button Clicks in PyQgis application

Hi guys I am relatively new to PyQt. I am trying create a custom plugin for Qgis which enables the user to select some features by drawing polygon on the canvas using mouse clicks and then performs intersection of the selected features with another layer. What I want to do is that when user right clicks on the canvas the polygon selection should stop. For this I have to identify between the right and left mouse signals. I have made a dummy function just to test this functionality:
def mousePressEvent(self):
print "code enters mousePressEvent function"
if event.buttons() == "Qt::LeftButton"
print"Left button pressed"
I am calling this function as follows:
QObject.connect(self.clickTool,SIGNAL("canvasClicked(QMouseEvent,Qt::MouseButton)"),self.mousePressEvent)
But I am unable to call the function. I guess I am doing something wrong in canvasClicked section. Any help in this matter would be much appreciated. Thanks in advance :)
The best way to achieve this is to use the QgsMapToolEmitPoint object. An example would be:
In your code, create a variable called emitPoint and in the run() function set it:
self.emitPoint = QgsMapToolEmitPoint(self.mapCanvas)
QObject.connect(
self.emitPoint,
SIGNAL("canvasClicked(const QgsPoint &, Qt::MouseButton)"),
self.clickedOnMap)
and create a function:
def clickedOnMap(self, pointOnMap, buttonUsed):
if (button==Qt.LeftButton):
....
the buttonUsed parameter has one of the values in the enum Qt::MenuButtons (as you can see in the link: http://doc.qt.io/qt-4.8/qt.html#MouseButton-enum).

python tkinter: Custom menu while pulling down

I'm learning creating software with Python and Tkinter. Now I need to change menu items for different conditions, but could not find an easy way to do it. Well, let me try to explain my question clearly using an example:
Like shown in the figure, I have a listbox on the left and a listbox on the right. I also have a menu to move the items around, the commands are "move to right", "move to left" and "exchange". The following conditions are considered:
When I only get items selected in left listbox, I want only the command "move to right" enabled, like shown in the figure.
When I only get items selected in right listbox, I want only the command "move to left" enabled.
When I get items selected in both listboxes, I want all commands enabled.
When I get no item selected, I want all commands disabled.
I know I can get the work done by binding events "ListboxSelect" and "Button-1" to some functions, and then use the functions to configure the menu. But it is really a complex work when I have five listboxes in the actual software. So I am wondering whether there is an easy way to do this, like overloading some functions in tkinter.Menu class (I tried overloading post(), grid(), pack() and place(), none of them works).
Any idea is welcomed.
I think what you want to use is the postcommand to modify the menu as appropriate. If you're going to have multiple listboxes, the simplest solution may be to implement your own class. Here's a rough idea:
class EditMenu(Tkinter.Menu):
def __init__(self, parent, listboxes, **kw):
self.commandhook = kw.get('postcommand', None)
kw['postcommand'] = self.postcommand
super(EditMenu, self).__init__(parent, **kw)
self.listboxes = listboxes
self.add_command(label="Move to right", command=self.move_to_right)
self.add_command(label="Move to left", command=self.move_to_left)
self.add_command(label="Exchange", command=self.exchange)
def postcommand(self):
for i in xrange(3):
# do some checks for each entry
# and set state to either Tkinter.DISABLED or Tkinter.NORMAL
self.entryconfig(i, state=state)
if self.commandhook is not None:
self.commandhook()
# Implement your three functions here
If you start to add more items, probably what you'll want to do is create a class for each menu item. In that class you could put in the logic for enable/disable and the callback function implementation. Comment if you'd like to see an example.

cursor gone in PyQT

I have a window containing multiple QRowWidgets, which are custom widgets defined by me. These QRowWidgets contain QLineEdits and other standard widgets. To show or hide certain parts of a QRowWidget, I overdefined the focusInEvent() methodes of all the widgets within it. It works perfectly, when I click on the QRowWidget, the hidden elements appear.
The weird thing is that the blinking cursor line hovewer doesn't appear in the QLineEdits within the custom widgets. I can select them both by a mouse click or with Tab, and a glow effect indicates that the QLineEdit is selected in it, I can select a text in it, or start typing at any location wherever I clicked, but the cursor never appears and it's quite annoying.
My 1st thought was that it is a bug on Mac, but I have the same experience on SuSe Linux.
I'm using python 2.7 and PyQt4.
This is in the __init__() of the QRowWidget:
for i in self.findChildren(QWidget):
i.focusInEvent = self.focusInEvent
And then this is the own focusInEvent():
def focusInEvent(self, event):
if self.pself.focusedLine:
self.pself.focusedLine.setStyleSheet("color: #666;")
self.pself.focusedLine.desc.hide()
self.pself.focusedLine.closebutton.hide()
self.setStyleSheet("color: #000;")
self.desc.show()
self.closebutton.show()
self.pself.focusedLine = self
I suspect you do not make a call to the original focusInEvent() when you override it. Your function should look something like:
def focusInEvent(self,...):
QParent.focusInEvent(self,...)
# the rest of your code
where QParent is the nearest base class for your widgets is.
Either that, or make sure you call focusInEvent() on your QLineEdit widgets as part of your function.
Given the comments, it sounds like you are dynamically reassigning the focusInEvent function on the insantiatations in your custom widget. I would either make a derived class for each of the widgets you use that just overrides focusInEvent as above, or include a line like
type(self).focusInEvent(self,..)
in you function.

Categories

Resources