I am working on Qt and using libVlc version 2.1.5 for live video streaming.I want to handle mouse press event on vlc frame.But when I click on vlc,it is not able to throw the mouse event.
I have tried with
libvlc_video_set_mouse_input(libvlcMediaPlayer,false);
But it hides the mouse over vlc.
Please help me if anyone knows.
Thanks.
You need to use libvlc_video_set_key_input function as well:
libvlc_video_set_mouse_input(media_player, 0);
libvlc_video_set_key_input(media_player, 0);
Three Solutions on Windows
Solution One: WS_EX_TRANSPARENT
Note: May not work on Windows 7 or below.
# Created by BaiJiFeiLong#gmail.com at 2022/2/10 23:31
import vlc
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore
def togglePlaying():
player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
player.get_state() == vlc.State.Playing and player.pause()
player.get_state() != vlc.State.Playing and player.play()
def onVideoOut(event):
hwnd = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
exStyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
exStyle |= win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exStyle)
app = QtWidgets.QApplication()
window = QtWidgets.QMainWindow()
window.setCentralWidget(QtWidgets.QWidget())
window.centralWidget().mousePressEvent = lambda *args: togglePlaying()
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()
filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(window.centralWidget().winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()
app.exec_()
Solution Two: Low-Level Mouse Hook
# Created by BaiJiFeiLong#gmail.com at 2022/2/10 23:31
from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG
import vlc
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore
def genStruct(name="Structure", **kwargs):
return type(name, (Structure,), dict(
_fields_=list(kwargs.items()),
__str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
))
#WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
msg = cast(lParam, POINTER(HookStruct))[0]
hwnd = win32gui.WindowFromPoint((msg.pt.x, msg.pt.y))
if hwnd in vlcHwnds:
win32gui.PostMessage(widget.winId(), wParam, wParam, (msg.pt.y << 16) + msg.pt.x)
return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))
def togglePlaying():
print("toggle")
player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
player.get_state() == vlc.State.Playing and player.pause()
player.get_state() != vlc.State.Playing and player.play()
def onVideoOut(event):
hwnd1 = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
hwnd2 = win32gui.GetWindow(hwnd1, win32con.GW_CHILD)
vlcHwnds.append(hwnd1)
vlcHwnds.append(hwnd2)
print("vlcHwnds", vlcHwnds)
app = QtWidgets.QApplication()
widget = QtWidgets.QWidget()
widget.mouseReleaseEvent = lambda *args: togglePlaying()
window = QtWidgets.QMainWindow()
window.setCentralWidget(widget)
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()
vlcHwnds = []
HookStruct = genStruct(
"Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
windll.user32.SetWindowsHookExW(win32con.WH_MOUSE_LL, hookProc, None, 0)
filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(widget.winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()
app.exec_()
Solution Three: In-Process Mouse Hook
# Created by BaiJiFeiLong#gmail.com at 2022/2/10 23:31
from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG, HINSTANCE
import vlc
import win32api
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore
def genStruct(name="Structure", **kwargs):
return type(name, (Structure,), dict(
_fields_=list(kwargs.items()),
__str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
))
#WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
msg = cast(lParam, POINTER(HookStruct))[0]
win32gui.PostMessage(widget.winId(), wParam, wParam, (msg.pt.y << 16) + msg.pt.x)
return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))
def togglePlaying():
player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
player.get_state() == vlc.State.Playing and player.pause()
player.get_state() != vlc.State.Playing and player.play()
def onVideoOut(event):
hwnd1 = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
processId = win32api.GetModuleHandle()
threadId = windll.user32.GetWindowThreadProcessId(hwnd1, None)
windll.user32.SetWindowsHookExW(win32con.WH_MOUSE, hookProc, HINSTANCE(processId), threadId)
app = QtWidgets.QApplication()
window = QtWidgets.QMainWindow()
widget = QtWidgets.QWidget()
widget.mouseReleaseEvent = lambda *args: togglePlaying()
window.setCentralWidget(widget)
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()
HookStruct = genStruct(
"Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(widget.winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()
app.exec_()
I have used libvlc 2.2.2 under Ubuntu 16 and managed to get mouse events on vlc video area in following way (providing only code relevant to the issue). In my VideoPlayer class I have members:
libvlc_media_player_t* vlcPlayer;
VideoWidget* widget;
, where VideoWidget is my custom widget class. In cpp I set libvlc_video_set_mouse_input(vlcPlayer, false);, create widget instance, pass it to my UI and when "play" video is called i also pass widget to vlc libvlc_media_player_set_xwindow(vlcPlayer, widget->winId());
My custom VideoWidget class is following:
// header
class VideoWidget : public QFrame
{
public:
VideoWidget(QWidget* parent = Q_NULLPTR);
protected:
void mousePressEvent(QMouseEvent* event) override;
};
// cpp
VideoWidget::VideoWidget(QWidget* parent)
: QFrame(parent)
{
}
void VideoWidget::mousePressEvent(QMouseEvent* event)
{
qDebug() << "mouse press";
QFrame::mousePressEvent(event);
}
So the idea is to catch mouse events with QWidget passed to vlc.
Related
To start with, I am not a developer, but a mere automation engineer that have worked a bit with coding in Java, python, C#, C++ and C.
I am trying to make a prototype that take pictures and stores them using a digital pin on the board. Atm I can take pictures using a switch, but it is really slow(around 3 seconds pr image).
My complete system is going to be like this:
A product passes by on a conveyor and a photo cell triggers the board to take an image and store it. If an operator removes a product(because of bad quality) the image is stored in a different folder.
I started with the snapshot function shipped with Mendel and have tried to get rid off the overhead, but the Gstream and pipeline-stuff confuses me a lot.
If someone could help me with how to understand the supplied code, or how to write a minimalistic solution to take an image i would be grateful :)
I have tried to understand and use project-teachable and examples-camera from Google coral https://github.com/google-coral, but with no luck. I have had the best luck with the snapshot tool that uses snapshot.py that are referenced here https://coral.withgoogle.com/docs/camera/datasheet/#snapshot-tool
from periphery import GPIO
import time
import argparse
import contextlib
import fcntl
import os
import select
import sys
import termios
import threading
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstBase', '1.0')
from functools import partial
from gi.repository import GLib, GObject, Gst, GstBase
from PIL import Image
GObject.threads_init()
Gst.init(None)
WIDTH = 2592
HEIGHT = 1944
FILENAME_PREFIX = 'img'
FILENAME_SUFFIX = '.png'
AF_SYSFS_NODE = '/sys/module/ov5645_camera_mipi_v2/parameters/ov5645_af'
CAMERA_INIT_QUERY_SYSFS_NODE = '/sys/module/ov5645_camera_mipi_v2/parameters/ov5645_initialized'
HDMI_SYSFS_NODE = '/sys/class/drm/card0/card0-HDMI-A-1/status'
# No of initial frames to throw away before camera has stabilized
SCRAP_FRAMES = 1
SRC_WIDTH = 2592
SRC_HEIGHT = 1944
SRC_RATE = '15/1'
SRC_ELEMENT = 'v4l2src'
SINK_WIDTH = 2592
SINK_HEIGHT = 1944
SINK_ELEMENT = ('appsink name=appsink sync=false emit-signals=true '
'max-buffers=1 drop=true')
SCREEN_SINK = 'glimagesink sync=false'
FAKE_SINK = 'fakesink sync=false'
SRC_CAPS = 'video/x-raw,format=YUY2,width={width},height={height},framerate={rate}'
SINK_CAPS = 'video/x-raw,format=RGB,width={width},height={height}'
LEAKY_Q = 'queue max-size-buffers=1 leaky=downstream'
PIPELINE = '''
{src_element} ! {src_caps} ! {leaky_q} ! tee name=t
t. ! {leaky_q} ! {screen_sink}
t. ! {leaky_q} ! videoconvert ! {sink_caps} ! {sink_element}
'''
def on_bus_message(bus, message, loop):
t = message.type
if t == Gst.MessageType.EOS:
loop.quit()
elif t == Gst.MessageType.WARNING:
err, debug = message.parse_warning()
sys.stderr.write('Warning: %s: %s\n' % (err, debug))
elif t == Gst.MessageType.ERROR:
err, debug = message.parse_error()
sys.stderr.write('Error: %s: %s\n' % (err, debug))
loop.quit()
return True
def on_new_sample(sink, snapinfo):
if not snapinfo.save_frame():
# Throw away the frame
return Gst.FlowReturn.OK
sample = sink.emit('pull-sample')
buf = sample.get_buffer()
result, mapinfo = buf.map(Gst.MapFlags.READ)
if result:
imgfile = snapinfo.get_filename()
caps = sample.get_caps()
width = WIDTH
height = HEIGHT
img = Image.frombytes('RGB', (width, height), mapinfo.data, 'raw')
img.save(imgfile)
img.close()
buf.unmap(mapinfo)
return Gst.FlowReturn.OK
def run_pipeline(snapinfo):
src_caps = SRC_CAPS.format(width=SRC_WIDTH, height=SRC_HEIGHT, rate=SRC_RATE)
sink_caps = SINK_CAPS.format(width=SINK_WIDTH, height=SINK_HEIGHT)
screen_sink = FAKE_SINK
pipeline = PIPELINE.format(
leaky_q=LEAKY_Q,
src_element=SRC_ELEMENT,
src_caps=src_caps,
sink_caps=sink_caps,
sink_element=SINK_ELEMENT,
screen_sink=screen_sink)
pipeline = Gst.parse_launch(pipeline)
appsink = pipeline.get_by_name('appsink')
appsink.connect('new-sample', partial(on_new_sample, snapinfo=snapinfo))
loop = GObject.MainLoop()
# Set up a pipeline bus watch to catch errors.
bus = pipeline.get_bus()
bus.add_signal_watch()
bus.connect('message', on_bus_message, loop)
# Connect the loop to the snaphelper
snapinfo.connect_loop(loop)
# Run pipeline.
pipeline.set_state(Gst.State.PLAYING)
try:
loop.run()
except:
pass
# Clean up.
pipeline.set_state(Gst.State.NULL)
while GLib.MainContext.default().iteration(False):
pass
class SnapHelper:
def __init__(self, sysfs, prefix='img', oneshot=True, suffix='jpg'):
self.prefix = prefix
self.oneshot = oneshot
self.suffix = suffix
self.snap_it = oneshot
self.num = 0
self.scrapframes = SCRAP_FRAMES
self.sysfs = sysfs
def get_filename(self):
while True:
filename = self.prefix + str(self.num).zfill(4) + '.' + self.suffix
self.num = self.num + 1
if not os.path.exists(filename):
break
return filename
#def check_af(self):
#try:
# self.sysfs.seek(0)
# v = self.sysfs.read()
# if int(v) != 0x10:
# print('NO Focus')
#except:
# pass
# def refocus(self):
# try:#
# self.sysfs.write('1')
# self.sysfs.flush()
# except:
# pass
def save_frame(self):
# We always want to throw away the initial frames to let the
# camera stabilize. This seemed empirically to be the right number
# when running on desktop.
if self.scrapframes > 0:
self.scrapframes = self.scrapframes - 1
return False
if self.snap_it:
self.snap_it = False
retval = True
else:
retval = False
if self.oneshot:
self.loop.quit()
return retval
def connect_loop(self, loop):
self.loop = loop
def take_picture(snap):
start_time = int(round(time.time()))
run_pipeline(snap)
print(time.time()- start_time)
def main():
button = GPIO(138, "in")
last_state = False
with open(AF_SYSFS_NODE, 'w+') as sysfs:
snap = SnapHelper(sysfs, 'test', 'oneshot', 'jpg')
sysfs.write('2')
while 1:
button_state = button.read()
if(button_state==True and last_state == False):
snap = SnapHelper(sysfs, 'test', 'oneshot', 'jpg')
take_picture(snap)
last_state = button_state
if __name__== "__main__":
main()
sys.exit()
Output is what i expect, but it is slow.
I switched to a USB-webcam and used the pygame library instead.
I am currently working on a Note taking app in pyGtk and have set up a TextView where a user can type and add text tags for Bold Underline and Italics.
However, when it comes to saving the formatted text I cannot figure out how to do so.
I am trying to save in Gtk's native tagset format however after using
tag_format = TextBuffer.register_serialize_tagset()
content = TextBuffer.serialize(self, tag_format, start,end)
I cannot write this to a file with
open(filename, 'w').write(content)
because I get an error which states that it cannot write in bytes and needs a string instead.
I am currently working on a Note taking app in pyGtk and have set up a TextView where a user can type and add text tags for Bold Underline and Italics.
However, when it comes to saving the formatted text I cannot figure out how to do so.
I am trying to save in Gtk's native tagset format however after using
tag_format = TextBuffer.register_serialize_tagset()
content = TextBuffer.serialize(self, tag_format, start,end)
I cannot write this to a file with
open(filename, 'w').write(content)
because I get an error which states that it cannot write in bytes and needs a string instead.
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango
I am currently working on a Note taking app in pyGtk and have set up a TextView where a user can type and add text tags for Bold Underline and Italics.
However, when it comes to saving the formatted text I cannot figure out how to do so.
I am trying to save in Gtk's native tagset format however after using
tag_format = TextBuffer.register_serialize_tagset()
content = TextBuffer.serialize(self, tag_format, start,end)
I cannot write this to a file with
open(filename, 'w').write(content)
because I get an error which states that it cannot write in bytes and needs a string instead.
File "example.py", line 87, in save_file
open(filename, 'w').write(content)
TypeError: write() argument must be str, not bytes
Here is sample code you can run and test by typing and then saving
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango
class MainWindow(Gtk.ApplicationWindow):
def __init__(self):
Gtk.Window.__init__(self, title = "TwoNote")
self.grid = Gtk.Grid()
self.toolbar = Gtk.Toolbar()
self.grid.add(self.toolbar)
#buttons for toolbar
self.button_bold = Gtk.ToggleToolButton()
self.button_italic = Gtk.ToggleToolButton()
self.button_underline = Gtk.ToggleToolButton()
self.button_save = Gtk.ToolButton()
self.button_open = Gtk.ToolButton()
self.mytext = TextSet(self.button_bold, self.button_italic, self.button_underline)
self.button_bold.set_icon_name("format-text-bold-symbolic")
self.toolbar.insert(self.button_bold, 0)
self.button_italic.set_icon_name("format-text-italic-symbolic")
self.toolbar.insert(self.button_italic, 1)
self.button_underline.set_icon_name("format-text-underline-symbolic")
self.toolbar.insert(self.button_underline, 2)
self.toolbar.insert(self.button_save, 3)
self.toolbar.insert(self.button_open, 4)
self.button_open.set_icon_name("document-open-data")
self.button_save.set_icon_name("document-save")
self.button_save.connect("clicked", self.save_file)
self.button_open.connect("clicked", self.open_file)
self.button_bold.connect("toggled", self.mytext.on_button_clicked, "Bold", self.button_italic, self.button_underline)
self.button_italic.connect("toggled", self.mytext.on_button_clicked, "Italic", self.button_bold, self.button_underline)
self.button_underline.connect("toggled", self.mytext.on_button_clicked, "Underline", self.button_bold, self.button_italic)
self.grid.attach_next_to(self.mytext, self.toolbar, Gtk.PositionType.BOTTOM, 10,30)
self.add(self.grid)
filename = "Untitled"
def open_file(self, widget):
open_dialog = Gtk.FileChooserDialog("Open an existing file", self, Gtk.FileChooserAction.OPEN,(Gtk.STOCK_CANCEL,Gtk.ResponseType.CANCEL,Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
open_response = open_dialog.run()
if open_response == Gtk.ResponseType.OK:
filename = open_dialog.get_filename()
text = open(filename).read()
self.mytext.get_buffer().set_text(text)
open_dialog.destroy()
elif open_response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
open_dialog.destroy()
def save_file(self, widget):
savechooser = Gtk.FileChooserDialog('Save File', self, Gtk.FileChooserAction.SAVE, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
allfilter = Gtk.FileFilter()
allfilter.set_name('All files')
allfilter.add_pattern('*')
savechooser.add_filter(allfilter)
txtFilter = Gtk.FileFilter()
txtFilter.set_name('Text file')
txtFilter.add_pattern('*.txt')
savechooser.add_filter(txtFilter)
response = savechooser.run()
if response == Gtk.ResponseType.OK:
filename = savechooser.get_filename()
print(filename, 'selected.')
buf = self.mytext.get_buffer()
start, end = buf.get_bounds()
tag_format = buf.register_serialize_tagset()
content = buf.serialize(buf, tag_format, start, end)
try:
open(filename, 'w').write(content)
except SomeError as e:
print('Could not save %s: %s' % (filename, err))
savechooser.destroy()
elif response == Gtk.ResponseType.CANCEL:
print('Closed, file not saved.')
savechooser.destroy()
class TextSet(Gtk.TextView):
def __init__(self, buttonBold, buttonItalic, buttonUnderline, interval = 1 ):
# Textview Setup
Gtk.TextView.__init__(self)
self.set_vexpand(True)
self.set_indent(10)
self.set_top_margin(90)
self.set_left_margin(20)
self.set_right_margin(20)
self.set_wrap_mode(Gtk.WrapMode.CHAR)
self.tb = TextBuffer()
self.set_buffer(self.tb)
# Thread setup
self.button_bold = buttonBold
self.button_italic = buttonItalic
self.button_underline = buttonUnderline
def on_button_clicked(self, widget, tagname, widget1, widget2):
state = widget.get_active()
name = widget.get_icon_name()
bounds = self.tb.get_selection_bounds()
self.tagname = tagname
if(state):
widget1.set_active(False)
widget2.set_active(False)
#highlighting
if(len(bounds) != 0):
start, end = bounds
myIter = self.tb.get_iter_at_mark(self.tb.get_insert())
myTags = myIter.get_tags()
if(myTags == [] and state == True):
self.tb.apply_tag_by_name(tagname, start, end)
elif(myTags != [] and state == True):
self.tb.remove_all_tags(start, end)
self.tb.apply_tag_by_name(tagname, start, end)
else:
for i in range(len(myTags)):
if(myTags[i].props.name == tagname):
self.tb.remove_tag_by_name(tagname,start,end)
myTags = []
self.tb.markup(widget, tagname)
def mouse_clicked(self, window, event):
self.button_bold.set_active(False)
self.button_italic.set_active(False)
self.button_underline.set_active(False)
class TextBuffer(Gtk.TextBuffer):
def __init__(self):
Gtk.TextBuffer.__init__(self)
self.connect_after('insert-text', self.text_inserted)
# A list to hold our active tags
self.taglist_on = []
# Our Bold tag.
self.tag_bold = self.create_tag("Bold", weight=Pango.Weight.BOLD)
self.tag_none = self.create_tag("None", weight=Pango.Weight.NORMAL)
self.tag_italic = self.create_tag("Italic", style=Pango.Style.ITALIC)
self.tag_underline = self.create_tag("Underline", underline=Pango.Underline.SINGLE)
def get_iter_position(self):
return self.get_iter_at_mark(self.get_insert())
def markup(self, widget, tagname):
self.tag_name = tagname
self.check = True
''' add "bold" to our active tags list '''
if(widget.get_active() == True):
if(self.tag_name == 'Bold'):
if 'Bold' in self.taglist_on:
del self.taglist_on[self.taglist_on.index('Bold')]
else:
self.taglist_on.append('Bold')
if(self.tag_name == 'Italic'):
if 'Italic' in self.taglist_on:
del self.taglist_on[self.taglist_on.index('Italic')]
else:
self.taglist_on.append('Italic')
if(self.tag_name == 'Underline'):
if 'Underline' in self.taglist_on:
del self.taglist_on[self.taglist_on.index('Underline')]
else:
self.taglist_on.append('Underline')
else:
self.check = False
def text_inserted(self, buffer, iter, text, length):
# A text was inserted in the buffer. If there are ny tags in self.tags_on, apply them
#if self.taglist_None or self.taglist_Italic or self.taglist_Underline or self.taglist_Bold:
if self.taglist_on:
# This sets the iter back N characters
iter.backward_chars(length)
# And this applies tag from iter to end of buffer
if(self.check == True):
if(self.tag_name == 'Italic'):
self.apply_tag_by_name('Italic', self.get_iter_position(), iter)
if(self.tag_name == 'Bold'):
self.apply_tag_by_name('Bold', self.get_iter_position(), iter)
if(self.tag_name == 'Underline'):
self.apply_tag_by_name('Underline', self.get_iter_position(), iter)
else:
self.remove_all_tags(self.get_iter_position(), iter)
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
I figured it out rather than using
open(filename, 'w').write(content)
to save the content I imported GLib and used
GLib.file_set_contents(filename, content)
Here is my code :
def er():
print("connection error")
from PyQt5.QtWidgets import QMessageBox
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Some text ")
msg.setInformativeText("info text")
msg.setWindowTitle("title")
msg.setStandardButtons(QMessageBox.Ok)
retval = msg.exec_()
print(retval)
if __name__ == '__main__':
mac = (':'.join(['{:02x}'.format((getnode() >> i) & 0xff) for i in range(0,8 * 6, 8)][::-1]))
if mac == 'b8:e8:56:24:96:30':
print("OK")
some_function
else:
er()
and the error is 'QWidget: Must construct a QApplication before a QWidget'
You have to init the qt event loop with QApplication first, like the error message said
def er():
print("connection error")
from PyQt5.QtWidgets import QMessageBox,QApplication
import sys
app = QApplication(sys.argv)
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Some text ")
msg.setInformativeText("info text")
msg.setWindowTitle("title")
msg.setStandardButtons(QMessageBox.Ok)
retval = msg.exec_()
print(retval)
if __name__ == '__main__':
mac = (':'.join(['{:02x}'.format((getnode() >> i) & 0xff) for i in range(0, 8 * 6, 8)][::-1]))
if mac == 'b8:e8:56:24:96:30':
print("OK")
some_function
else:
er()
How to refer to the text entry widget`s input in a subprocess.call() in Python GTK? App for calling bioinformatics tool from PyGTK:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import subprocess
class EntryExample:
def enter_callback(self, widget, entry):
entry_text = entry.get_text()
print "Entry contents: %s\n" % entry_text
def entry_toggle_editable(self, checkbutton, entry):
entry.set_editable(checkbutton.get_active())
def entry_toggle_visibility(self, checkbutton, entry):
entry.set_visibility(checkbutton.get_active())
def __init__(self):
# create a new window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(200, 100)
window.set_title("GTK Entry")
window.connect("delete_event", lambda w,e: gtk.main_quit())
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
entry = gtk.Entry()
entry.set_max_length(50)
entry.connect("activate", self.enter_callback, entry)
entry.set_text("Insert")
entry.insert_text(" SRA accession number", len(entry.get_text()))
entry.select_region(0, len(entry.get_text()))
vbox.pack_start(entry, True, True, 0)
entry.show()
hbox = gtk.HBox(False, 0)
vbox.add(hbox)
hbox.show()
# Create a new button for running Linux Shell script
buttonscript = gtk.Button(label="Download", stock=None)
# Connect the "clicked" signal of the button to the function
buttonscript.connect("clicked", runlinuxshell )
vbox.pack_start(buttonscript, True, True, 0)
buttonscript.set_flags(gtk.CAN_DEFAULT)
buttonscript.grab_default()
buttonscript.show()
button = gtk.Button(stock=gtk.STOCK_CLOSE)
button.connect("clicked", lambda w: gtk.main_quit())
vbox.pack_start(button, True, True, 0)
button.set_flags(gtk.CAN_DEFAULT)
button.grab_default()
button.show()
window.show()
def runlinuxshell ():
subprocess.call('$i=len(entry.get_text()) # Error is here
echo $i
./fastq-dump --split-files $i -v')
def main():
gtk.main()
return 0
if __name__ == "__main__":
EntryExample()
main()
How to pass text input from a widget into the suprocess.call()?
Is there any good example on how to call bioinformatics linux tools in PyGTK?
disclaimer: the sample uses pygobject with introspection and not pygtk which is deprecated for years and should not be used in new code.
disclaimer 2: the sample can be greatly improved to say the least, it's just an adaption of your original script.
You probably would do some like the following:
import gi
from gi.repository import Gtk
import subprocess
class EntryExample:
def __init__(self):
window = Gtk.Window()
window.set_size_request(200, 100)
window.set_title("GTK Entry")
window.connect("delete_event", Gtk.main_quit)
vbox = Gtk.VBox(False, 0)
window.add(vbox)
self.entry = Gtk.Entry()
self.entry.set_max_length(50)
self.entry.set_text("SRA accession number")
vbox.pack_start(self.entry, True, True, 0)
buttonscript = Gtk.Button(label="Download", stock=None)
buttonscript.connect("clicked", self.runlinuxshell)
vbox.pack_start(buttonscript, True, True, 0)
button = Gtk.Button(stock=Gtk.STOCK_CLOSE)
button.connect("clicked", Gtk.main_quit)
vbox.pack_start(button, True, True, 0)
window.show_all()
def runlinuxshell (self, widget):
mylen = len(self.entry.get_text())
# Here you will execute your subprocess with mylen
def main(self):
Gtk.main()
if __name__ == "__main__":
sub = EntryExample()
sub.main()
recently I started learning Jython and now I have rather simply problem. I would like to improve quality of my animation. Unfortunately I don't know how to add double buffering to my applet . Could you help me?
Best regards!
from javax.swing import JToolBar
from javax.swing import JButton
from javax.swing import JFrame
import time
from java import awt
from java.awt import BorderLayout
class Canvas(awt.Canvas):
u"Canvas - drawing area"
def __init__(self,winSize = 400):
self.play = False
self.background=awt.Color.black
self.winSize = winSize
self.l = 0
def playSim(self, play):
if play == True:
self.play = True
self.repaint()
else: self.play = False
def paint(self, g):
g.fillRect(50, int(self.winSize/4), self.l, int(self.winSize/2))
if self.l < self.winSize: self.l += 1
else: self.l = 0
time.sleep(0.02)
if self.play == True: self.repaint()
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
winSize = 600
toolbar = JToolBar()
self.playButton = JButton("Start", actionPerformed=self.playButtonPress )
toolbar.add(self.playButton)
self.add(toolbar, BorderLayout.NORTH)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(winSize, winSize)
self.setResizable(False)
self.setLocationRelativeTo(None)
self.setVisible(True)
self.canvas = Canvas(winSize)
self.getContentPane().add(self.canvas)
self.setTitle("TEST")
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
def playButtonPress(self, e):
if self.playButton.getLabel() == "Start":
self.canvas.playSim(True)
self.playButton.setLabel("Stop")
else:
self.playButton.setLabel("Start")
self.canvas.playSim(False)
if __name__ == '__main__':
Example()
I solved my recent problem:
from javax.swing import JToolBar
from javax.swing import JButton
from javax.swing import JFrame
import time
from java import awt
from java.awt import BorderLayout
class Canvas(awt.Canvas):
u"Canvas - drawing area"
def __init__(self,winSize = 400):
self.play = False
self.background=awt.Color.black
self.winSize = winSize
self.l = 0
self.bi = BufferedImage(winSize, winSize, BufferedImage.TYPE_INT_RGB)
self.offScreenGraphics = self.bi.getGraphics()
def playSim(self, play):
if play == True:
self.play = True
self.repaint()
else: self.play = False
def paint(self, g):
self.offScreenGraphics.fillRect(50, int(self.winSize/4), self.l, int(self.winSize/2))
if self.l < self.winSize: self.l += 1
else: self.l = 0
g.drawImage(self.bi, 0, 0, None)
time.sleep(0.02)
if self.play == True: self.repaint()
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
winSize = 600
toolbar = JToolBar()
self.playButton = JButton("Start", actionPerformed=self.playButtonPress )
toolbar.add(self.playButton)
self.add(toolbar, BorderLayout.NORTH)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(winSize, winSize)
self.setResizable(False)
self.setLocationRelativeTo(None)
self.setVisible(True)
self.canvas = Canvas(winSize)
self.getContentPane().add(self.canvas)
self.setTitle("TEST")
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
def playButtonPress(self, e):
if self.playButton.getLabel() == "Start":
self.canvas.playSim(True)
self.playButton.setLabel("Stop")
else:
self.playButton.setLabel("Start")
self.canvas.playSim(False)
if __name__ == '__main__':
Example()
Now I've another(rather trivial) problem:
How can I make from this python file *the class file* which would be ready to publish it on website as an applet?