How to test QRadioButton with QtBot? [duplicate] - pyqt5

Here is my code:
from PySide import QtCore, QtGui, QtTest
import sys
application = QtGui.QApplication(sys.argv)
checkbox = QtGui.QCheckBox()
assert not checkbox.isChecked()
QtTest.QTest.mouseClick(checkbox, QtCore.Qt.LeftButton)
assert checkbox.isChecked()
I expected the checkbox to become checked after the simulated mouse click. But it doesn't. I'm on Mac OS X, Python 2.7 with a freshly brew installed PySide.

I ran into the same problem. In my case the default click position was incorrect. The documentation states that the default position is the center of the widget.
>>> print checkbox.rect()
PySide.QtCore.QRect(0,0,640,480)
All the other examples use push buttons which, can be set to any size, so it will fill the entire available space. The checkbox, however, cannot be resized.
Since I can't actually see the checkbox, I assumed that it was horizontally on the left and vertically in the middle.
>>> QTest.mouseClick(checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2,checkbox.height()/2)
>>> print checkbox.isChecked()
True

Related

Different behaviour of ipywidgets.interactive_output() on Windows and macOS

I wanted to learn how to use interactive plots in Jupyter Notebook and created a script that updates a figure based on the current values of two sliders. The idea is simply that when the value of one of the sliders changes the figure should be updated.
This worked fine when I first ran the code on my Windows PC (using Windows 10). However, when I then ran the same code on my MacBook (using macOS Monterey 12.6.1), the figure is not updated but a new figure is created every time I change the value of one of my sliders.
Please find a MWE below:
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
%matplotlib widget
# Create two sliders
slider1 = widgets.IntSlider(value=4, min=0, max=10, step=1,
description='Slider1', continuous_update = False)
slider2 = widgets.IntSlider(value=8, min=0, max=10, step=1,
description='Slider2', continuous_update = False)
# Some function that plots the result based on the current values of the sliders
def plotResult(a, b):
plt.close('all')
plt.figure()
plt.hlines(a+b, xmin=0, xmax=10)
# Create interactive plot
interactive_plot = widgets.interactive_output(plotResult, {"a":slider1, "b":slider2})
ui = widgets.HBox([slider1, slider2])
display(ui, interactive_plot)
When I run the above code in a cell in my Jupyter Notebook, I get the following output:
(https://i.stack.imgur.com/NX02T.png).
When I now change any of the sliders, on Windows my figure is "updated in-place", while on macOS a new figure is created everytime (every figure newly created figure is labeled as 'Figure 1'). I don't understand why this is happening as I explicitly close all currently opening figures at the beginning of plotResults(a,b) by using the command plt.close('all').
I thought that since every newly created figure on macOS is labeled 'Figure 1' the problem could be that on macOS the cells are not refreshed. Thus, I additionally imported the module IPython using import IPython and then added the command IPython.display.clear_output(wait=True) after the first line of plotResults(a,b). However, this did not work and the problem persisted.
I also tried to use a different Matplotlib backend such as %matplotlib ipympl or %matplotlib nbagg instead of %matplotlib widget but this also did not help anything.

Is it possible to store values from ipywidgets to cell code like Google colab Form

When I use Google Colab Form and change field value, new value stored in cell code. So next time I open notebook I see new value in cell.
How can I use same functionality for ipywidgets field?
For example.
Cell with Colab Form:
slices = 4 ##param {type:"slider", min:1, max:10, step:0}
Cell with ipywidget:
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
# interact() syntax
def f(x):
return x
interact(f, x=10);
# classic syntax
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='d'
)
In Google Colab Form changed slider value injects into cell code.
But I didn't find same functionality for ipywidgets. If I move slider - its new value will be lost on notebook reload.
Maybe some tricks exists for this?

Jupyter-lab pyplot cell re-evaluation breaks interactive widget display

This code works as expected on a cleanly started kernel, but on re-executing the second cell, instead of an interactive widget (ipypml per https://matplotlib.org/3.3.0/users/interactive.html ), I get just the text output as in the image.
How are jupyter, jupyter-lab, widgets, pyplot, and matplotlib interacting to cause this problem?
And how do I properly do a plot so that I can re-execute the cell without re-starting the kernel?
Cell 0:
%matplotlib widget
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
Cell 1:
fig,ax = plt.subplots(num=0)
ax.plot(np.arange(4))
Cell 1 output:
[<matplotlib.lines.Line2D at 0x161b913a0>]
I found that I need to make sure the figure gets cleanly opened (or closed and re-opened) in each update. I had used the plt.subplots(num=0) option to keep repeated updates from creating new, non-displayed figures. (note that the 2nd cell in the screenshot has a been re-executed 5 times and has a [6] prefix)
plt.close(0)
fig,ax = plt.subplots(num=0)
ax.plot(np.arange(4))

pygame from a ssh session : how to display on attached screen? [duplicate]

I have a simple Pygame program:
#!/usr/bin/env python
import pygame
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
But every time I try to run it, I get this:
pygame 2.0.0 (SDL 2.0.12, python 3.8.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
And then nothing happens.
Why I can't run this program?
Your application works well. However, you haven't implemented an application loop:
import pygame
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()
run = True
while run:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# update game objects
# [...]
# clear display
win.fill((0, 0, 0))
# draw game objects
# [...]
# update display
pygame.display.flip()
# limit frames per second
clock.tick(60)
pygame.quit()
The typical PyGame application loop has to:
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
limit frames per second to limit CPU usage with pygame.time.Clock.tick
repl.it/#Rabbid76/PyGame-MinimalApplicationLoop See also Event and application loop
This is interesting. Computer read your program line by line[python]. When all the line are interpreted, the program closed. To solve this problem you need to add a while loop to make sure the program will continue until you close the program.
import pygame,sys
from pygame.locals import *
pygame.init()
pygame.display.set_caption("My first game")
win = pygame.display.set_mode((400,400))
#game loop keeps the game running until you exit the game.
game_running=True
while game_running:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
win.fill((0, 250, 154)) #Fill the pygame window with specific color. You can use hex or rgb color
pygame.display.update() #Refresh the pygame window
You can check more pygame Examples.
https://github.com/01one/Pygame-Examples
I think this will be helpful.

IPython plotting inline not showing

I have the following code in IPython running IPython QT Console on Linux.
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.
fig = figure()
ax = fig.add_axes()
ax = fig.add_axes([0,500, 0, 5000])
ax.plot([1,2,3,44], [4,4,55,55])
Out[5]: [<matplotlib.lines.Line2D at 0x3d8e7d0>]
fig
Out[6]: <matplotlib.figure.Figure at 0x3d25fd0>
fig.show()
/usr/lib/pymodules/python2.7/matplotlib/figure.py:362: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
"matplotlib is currently using a non-GUI backend, "
I've been struggling to make this work for some time, I've tried changing the backend manually with matplotlib.use() to Qt4Agg, GTK etc with no luck. This also happens in IPython notebook even when I call display().
Any ideas how to get the inline plotting working?
Marked Jakob's answer as the answer, but both are true actually. I had to replace the matploblibrc file with a new copy, started IPython QT Console with --pylab=None then manually entered %pylab inline in the console. Somehow this fixed the problem.
The axis object is defined incorrectly, this prevents matplotlib from rendering.
Remove the first ax = fig.add_axes(), and replace the second line with
ax = fig.add_axes([0, 0, 1, 1]).
The add_axes method requests the size of the axis in relative coordinates, in the form left, bottom, width, height with values between 0 and 1, see e.g. matplotlib tutorial.
You may also try fig.add_subplot(111) instead of fig.add_axes() or fig,ax = subplots() to create your figure and axis objects. The latter assumes that you have populated the interactive namespace matplotlib (%pylab) call in IPython.
It looks like your matplotlib build was compiled without a gui backend.
This is done when either a) it's explicitly specified (handy for webservers), or b) the required libraries for at least one gui backend aren't present (e.g. no Tk, Gtk, Qt, etc).
How did you install matplotlib?
If you compiled it from source, make sure that you have the development libraries for at least Tk installed and that your python install was compiled with Tk support (it is by default). If you installed it from your distro's repositories, whoever built the package built it without gui support, and you'll need to install it from another source.