How to use a custom GTK widget written in Vala from Python? - python-3.x

Recently i managed to make a shared library that i could use from this Vala file with these commands:
1:valac circular-progress-bar.vala -X -fPIC -X -shared -o test_shared.so --library=testShared --gir testShared-0.1.gir --pkg gtk+-3.0
2: g-ir-compiler --shared-library=test_shared.so --output=testShared-0.1.typelib testShared-0.1.gir
I made a simple test window in python which shows the widget and it only shows the text. Is it Python or it simply can't be used in this way ?
Image of the test window/app
I tried finding function to change settings or some value but i can't find it.
I would appreciate any help given !

After you've gone through the difficult technical steps of compiling an object and generating interface files to use the widget in Python, this answer may be a bit of a shock. As far as I can tell the reason no circle is showing is because the value is 0% - so no circle!
The widget has a percentage property and this can be set in Python with pb.props.percentage. In this example the percentage is set to 60% and works fine for me. I use pb.props.percentage = 0.6:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GObject
gi.require_version('testShared', '0.1')
from gi.repository import testShared
class GUI (Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
pb = testShared.CircularProgressBar()
pb.props.percentage = 0.6
self.connect('destroy', self.on_window_destroy)
self.add(pb)
self.show_all()
Gtk.main()
def on_window_destroy(self, window):
Gtk.main_quit()
if __name__ == "__main__":
GUI()
The widget has other properties that can be changed, e.g. line_width sets the width of the line that draws the circle.
Here is a screenshot showing the 60% and the line_width set to 10:

Related

grab image from clipbroad fuction pyhon in linux

I am looking for a method in which I can grab the image which is on the clipboard and assign it to the background of a pygame screen. I am trying to make an app in which a user can quickly annotate a captured image in linux. Below is a an example of what I am talking about. Unfortunately these modules do not work in linux. It's not the complete code and I have just included it to make my question clearer.
import pygame
from PIL import ImageTk, ImageGr
pygame.init()
def backgroundimage():
while True:
clipimage = ImageGrab.grabclipboard()
screen = pygame.display.set_mode(([800,800]), pygame.NOFRAME)
screen.fill((clipimage))
if __name__ == '__main__':
backgroundimage()

PyQt5 GUI freeze caused by Windows focus-follows-mouse

When Windows focus-follows-mouse-without-raising-the-window is enabled by either of the two methods linked to below, I consistently get PyQt5 GUI 'freezes' where you have to type any character in the terminal that you ran python from in order to unfreeze the GUI; complete description and test case (Windows 10, Python 3.6.1, PyQt5) is here: pyqt5 click in terminal causes GUI freeze
To enable the focus-follows-mouse-without-raise behavior, try either of these - they both work in Windows 10:
downloadable program ('X-Mouse' though that name is used by other programs):
https://joelpurra.com/projects/X-Mouse_Controls/
registry hack description:
https://sinewalker.wordpress.com/2010/03/10/ms-windows-focus-follows-mouse-registry-hacks/
So - a few questions:
can anyone reproduce the issue? It seems 100% reproducible for me, but it would be great to hear the same from someone else.
is there a way to change the python code to detect-and-circumvent focus-follows-mouse, or just to be immune to it, i.e. maybe by ensuring the GUI application always takes focus back again when you - for example - click in a dialog or qmessagebox owned by the main GUI window, or by some other means? (Is the object hierarchy set up optimally, and if not, maybe this could all be resolved by correcting the ownership structure?)
The brute-force solution seems to work, though I'd like to leave this question open to see if someone knows of a more optimal solution; it took a fair amount of searching to figure out the right way; mainly by taking a look a the open-source code for X-Mouse. Basically, this method takes effect immediately, whereas the registry hack doesn't take effect until reboot.
New version of pyqt_freeze_testcase.py (the file from the referenced stackoverflow question); the changes are only additions, noted between lines of hash marks:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
####################### added begin:
import win32gui
import win32con
####################### added end
# import the UI file created with pyuic5
from minimal_ui import Ui_Dialog
class MyWindow(QDialog,Ui_Dialog):
def __init__(self,parent):
QDialog.__init__(self)
self.parent=parent
self.ui=Ui_Dialog()
self.ui.setupUi(self)
################################# added begin:
self.initialWindowTracking=False
try:
self.initialWindowTracking=win32gui.SystemParametersInfo(win32con.SPI_GETACTIVEWINDOWTRACKING)
except:
pass
if self.initialWindowTracking:
print("Window Tracking was initially enabled. Disabling it for now; will re-enable on exit.")
win32gui.SystemParametersInfo(win32con.SPI_SETACTIVEWINDOWTRACKING,False)
################################# added end
def showMsg(self):
self.really1=QMessageBox(QMessageBox.Warning,"Really?","Really do stuff?",
QMessageBox.Yes|QMessageBox.No,self,Qt.WindowTitleHint|Qt.WindowCloseButtonHint|Qt.Dialog|Qt.MSWindowsFixedSizeDialogHint|Qt.WindowStaysOnTopHint)
self.really1.show()
self.really1.raise_()
if self.really1.exec_()==QMessageBox.No:
print("nope")
return
print("yep")
################################## added begin:
def closeEvent(self,event):
if self.initialWindowTracking:
print("restoring initial window tracking behavior ("+str(self.initialWindowTracking)+")")
win32gui.SystemParametersInfo(win32con.SPI_SETACTIVEWINDOWTRACKING,self.initialWindowTracking)
################################## added end
def main():
app = QApplication(sys.argv)
w = MyWindow(app)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

How do I set the minimum size of a Gtk ButtonBox child?

I'm trying to set the minimum size of the buttons in this GtkButtonBox. Currently they seem to be fixed - approx 85 pixels I think.
Is this possible?
If not, is there another way in Gtk to get two small sized buttons to snuggle together like in the above picture rather than having them appear to be two separate buttons? For example GtkStackSwitcher may be something I could use but there doesn't appear to be a way to respond to click events for a button.
I've used this test program to create the above (Ubuntu 14.04, Gtk+3.10 and Python3):
from gi.repository import Gtk
import sys
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title="example", application=app)
self.set_default_size(350, 200)
self.set_border_width(10)
hbox = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
hbox.set_layout(Gtk.ButtonBoxStyle.EXPAND)
button = Gtk.Button(label="a")
hbox.add(button)
button2 = Gtk.Button(label="b")
hbox.add(button2)
self.add(hbox)
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MyWindow(self)
win.show_all()
def do_startup(self):
Gtk.Application.do_startup(self)
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
With regards to a question about the desktop environment I'm using.
I've tried Mate, Unity and Gnome-Shell. All work the same way. I've removed the title and those controls. Still the same thing happens. To me this looks more like a GTK issue.
I believe that GtkButtonBox imposes some layout constraints on its buttons that you may not want here. Try using buttons in just a regular GtkGrid, but give them the GTK_STYLE_CLASS_LINKED CSS class.
For each button, do:
button.get_style_context().add_class(Gtk.STYLE_CLASS_LINKED)

pyqt+maya = fatal error when click to context menu

i use pyqt in autodesk maya. all work but when i try connect a context menu to my elements - maya get fatal error and closed.
import maya.OpenMayaUI as mui
import maya.api.OpenMaya as om
import sip
from PyQt4 import QtGui, QtCore, uic
#----------------------------------------------------------------------
def getMayaWindow():
ptr = mui.MQtUtil.mainWindow()
return sip.wrapinstance(long(ptr), QtCore.QObject)
#----------------------------------------------------------------------
form_class, base_class = uic.loadUiType('X:/tools/Maya/windows/2014/python/UI/perforceBrowserWnd.ui')
#----------------------------------------------------------------------
# main window class
#----------------------------------------------------------------------
class PerforceWindow(base_class, form_class):
def __init__(self, parent=getMayaWindow()):
super(base_class, self).__init__(parent)
self.setupUi(self)
# Popup Menu is not visible, but we add actions from above
self.popMenu = QtGui.QMenu( self )
self.popMenu.addAction("revert", self.on_action_revert)
self.popMenu.addAction("submit", self.on_action_submit)
self.filesListWgt.customContextMenuRequested.connect( self.filesListWgtMenuRequested )
#------------------------------------------------------------------
def filesListWgtMenuRequested(self, pos):
self.popMenu.exec_( self.filesListWgt.mapToGlobal(pos) )
def on_action_revert(self):
print('on_action_revert')
def on_action_submit(self):
print('on_action_submit')
#----------------------------------------------------------------------
# window
#----------------------------------------------------------------------
def perforceBrowser2():
perforceBrowserWnd = PerforceWindow()
perforceBrowserWnd.show()
perforceBrowser2()
dialog created in qtdesigner. i set attribute contentMenuPolicy in designer on QListWidtet. when i right click on QListWidtet or any element - i see a context menu. but if i click a menu or dismiss it - maya get fatal error
and i see log text - function on_action_revert is called. but after that - maya crashed.
what i doing wrong?
update:
i try simple test. replace a menu to simple call a function:
replace connect to:
self.filesListWgt.customContextMenuRequested.connect( self.on_action_revert )
def on_action_revert(self):
print('on_action_revert')
this crash maya too
I tested your code along with your UI file on PyQt in Maya 2013 as well as on PySide (using a QtShim) on Maya 2014 and your code ran fine. Please check your PyQt build for Maya 2014.
I recommend attempting to run your code using PySide on Maya 2014. To do this you do not need to change any of your code base. You just need to modify a few imports. It is worth checking out these: Take a look at this. You can use this to write code that is compatible in both PyQt and PySide. https://github.com/rgalanakis/practicalmayapython/blob/master/src/chapter5/qtshim.py
And to load your ui file in PySide environment take a look at this article: http://www.jason-parks.com/artoftech/?p=579
PyQt and PySide are both just python wrappers for the Qt framework. They are identical apart from a very few differences. So your code base never needs to change no matter what you use to run it in.
P.s. But for whatever reason you are so particular for using PyQt for 2014, Please use these guides to build it: http://download.autodesk.com/us/support/files/maya_documentation/pyqtmaya2014.pdf and this one: http://around-the-corner.typepad.com/adn/2013/04/building-sip-and-pyqt-for-maya-2014.html
Maya specific PyQt builds are maintained in this Github repo maintained by Marcus Ottosson. You can grab the specific build for yourself and add it to PYTHONPATH. I had the same issue in Maya 2015 and this helped.
https://github.com/pyqt

Alternative for tkinter's askopenfilename

Currently I am using tkinter's askopenfilename in a quicklist editor for Ubuntu to get a file's name and location. Although it works fine, the look and feel is not native.
Is there an easy alternative dialogue window, to navigate and get a file's name and location?
You could try with wxPython FileDialog:
>>> import wx
>>> d = wx.FileDialog(None)
>>> d.ShowModal()
5101
>>>
It gives a more OS specific look
wxPython is arriving soon to py3k as the Phoenix project and there are already snapshots for windows and mac (see my comment below). If you want something more stable you can use pyQt QtGui.QFileDialog.
import sys
from PyQt4 import QtGui
class Dialog(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
filename = QtGui.QFileDialog.getOpenFileName()
print filename
app = QtGui.QApplication(sys.argv)
dialog = Dialog()
You have a more complete example here.
Zenity
Zenity's File Selection Dialog provides an easy and natively looking solution with the --file-selection option. The dialog provides a number of options.
See also Zenity's man pages.
In its simplest form:
#!/usr/bin/env python3
import subprocess
try:
file = subprocess.check_output(["zenity", "--file-selection"]).decode("utf-8").strip()
print(file)
except subprocess.CalledProcessError:
pass
Gtk's FileChooserDialog
Another option is Gtk's FileChooserDialog, which produces, as one might expect, perfectly natively looking file chooser dialog windows.

Resources