Skip to content

Instantly share code, notes, and snippets.

@mmolero
Created July 7, 2016 13:12
Show Gist options
  • Save mmolero/c3db18390aa71bb6b3cdcb9822483032 to your computer and use it in GitHub Desktop.
Save mmolero/c3db18390aa71bb6b3cdcb9822483032 to your computer and use it in GitHub Desktop.
CefBrowser using PySide on Windows/Linux/MacOX
from cefpython3 import cefpython
import sys, os
import platform
import ctypes
from PySide.QtGui import *
from PySide.QtCore import *
if platform.system() in "Linux":
Container = QX11EmbedContainer
elif platform.system() in ("Windows","Darwin"):
Container = QWidget
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__(None)
self.resize(1200,800)
self.view = CefWidget(self)
self.setCentralWidget(self.view)
self.view.embed()
def closeEvent(self, event):
self.view.browser.CloseBrowser()
class CefWidget(Container):
browser = None
def __init__(self, parent=None):
super(CefWidget, self).__init__(parent)
self.show()
def embed(self):
windowInfo = cefpython.WindowInfo()
if platform.system() in ("Linux", "Darwin"):
self.x = 0
self.y = 0
self.width = 1200
self.height = 800
windowInfo.SetAsChild(int(self.winIdFixed()),[self.x, self.y, self.width,self.height])
elif platform.system() in "Windows":
windowInfo.SetAsChild(int(self.winIdFixed()))
url = "http://www.google.com"
self.browser = cefpython.CreateBrowserSync(windowInfo,
browserSettings={},
navigateUrl= url)
def winIdFixed(self):
# PySide bug: QWidget.winId() returns <PyCObject object at 0x02FD8788>,
# there is no easy way to convert it to int.
try:
return int(self.winId())
except:
if sys.version_info[0] == 2:
ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p
ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [ctypes.py_object]
return ctypes.pythonapi.PyCObject_AsVoidPtr(self.winId())
elif sys.version_info[0] == 3:
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object]
return ctypes.pythonapi.PyCapsule_GetPointer(self.winId(), None)
def moveEvent(self, event):
pos = event.pos()
if platform.system() in "Linux":
self.x = pos.x()
self.y = pos.y()
self.browser.SetBounds(self.x, self.y, self.width, self.height)
elif platform.system() in "Windows":
cefpython.WindowUtils.OnSize(int(self.winIdFixed()), 0, 0, 0)
def resizeEvent(self, event):
size = event.size()
if platform.system() in "Linux":
self.width = size.width()
self.height = size.height()
self.browser.SetBounds(self.x, self.y, self.width, self.height)
elif platform.system() in "Windows":
cefpython.WindowUtils.OnSize(int(self.winIdFixed()), 0, 0, 0)
class CefApplication(QApplication):
timer = None
def __init__(self, args):
super(CefApplication, self).__init__(args)
self.createTimer()
def createTimer(self):
self.timer = QTimer()
self.timer.timeout.connect(self.onTimer)
self.timer.start(10)
def onTimer(self):
cefpython.MessageLoopWork()
def stopTimer(self):
self.timer.stop()
if __name__ == '__main__':
settings = {}
settings['debug']= False
# These directories must be set on Linux
if platform.system() in "Linux":
settings["locales_dir_path"] = cefpython.GetModuleDirectory() + "/locales"
settings["resources_dir_path"] = cefpython.GetModuleDirectory()
if platform.system() in "Darwin":
settings["locales_dir_path"] = cefpython.GetModuleDirectory() + "/locales"
settings["resources_dir_path"] = cefpython.GetModuleDirectory() + "/Resources"
settings["context_menu"] = {
"enabled": True,
"navigation": True, # Back, Forward, Reload
"print": False,
"view_source": False,
"external_browser": False, # Open in external browser
"devtools": True, # Developer Tools
}
settings["browser_subprocess_path"] = "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess")
# This option is required for the GetCookieManager callback
# to work. It affects renderer processes, when this option
# is set to True. It will force a separate renderer process
# for each browser created using CreateBrowserSync.
settings["unique_request_context_per_browser"] = True
if platform.system() in "Darwin":
g_switches = {
# On Mac it is required to provide path to a specific
# locale.pak file. On Win/Linux you only specify the
# ApplicationSettings.locales_dir_path option.
"locale_pak": cefpython.GetModuleDirectory()
+ "/Resources/en.lproj/locale.pak",
}
cefpython.Initialize(settings, g_switches)
else:
cefpython.Initialize(settings)
if platform.system() in "Linux":
cefpython.WindowUtils.InstallX11ErrorHandlers()
app = CefApplication(sys.argv)
mainWindow = MainWindow()
#mainWindow.showFullScreen()
mainWindow.show()
app.exec_()
app.stopTimer()
# Need to destroy QApplication(), otherwise Shutdown() fails.
# Unset main window also just to be safe.
del mainWindow
del app
cefpython.Shutdown()
@mmolero
Copy link
Author

mmolero commented Jul 7, 2016

Now it works well on Linux, Ubuntu 14.04 64 Bits CEFPython 51 and Windows 10 64 Bits CEFPython 31.2. However it does not work on OSX, 10.11 El Capitan CEFPython 31.2 yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment