How to capture keyboard events in wxWebView? - wxwidgets

I want to handle keyboard events for wxWebView but it seems that the rendering engine, in my case WebView2 (edge backend) eats all the events and does not allow them to propagate to the parents.
I have bound a handler for key down events but it does not work.
ctrl_->Bind( wxEVT_KEY_DOWN, &WxHtml::onKeyDown, this );
void onKeyDown( wxKeyEvent& evt )
{
fs::out << evt.GetKeyCode() << std::endl;
}
How should we get the events?
wx version: 3.2.1
OS: win 10
wxWebView backend: WebView2

As Igor said, some native windows, such as wxWebview, will consume all low level events such as key presses and mouse clicks so that they can't be handled with wxWidgets events.
In the case of wxWebview, you can use JavaScript to handle key presses on the window and then try to navigate to an anchor with the key code. If you then handle the navigating event for the wxWebview window, you can retrieve the key code from the url for that event. Here is an example:
#include <wx/wx.h>
#include <wx/webview.h>
#include <wx/uri.h>
#ifdef __WXMSW__
#include <wx/msw/webview_ie.h>
#endif
class MyFrame: public wxFrame
{
public:
MyFrame();
private:
void OnWebViewNavigating(wxWebViewEvent& event);
void OnKeyUp(wxKeyEvent&);
wxWebView* m_webView;
};
MyFrame::MyFrame()
:wxFrame(NULL, wxID_ANY, "Test Frame", wxDefaultPosition,
wxSize(600, 400))
{
#ifdef __WXMSW__
wxWebViewIE::MSWSetEmulationLevel(wxWEBVIEWIE_EMU_IE11);
#endif
m_webView = wxWebView::New(this, wxID_ANY);
wxString s =R"(<!DOCTYPE html>
<html lang="en">
<body>
<p>Hello</p>
<script>
document.onkeyup = function(e) {
let key_press = e.key;
let key_code = key_press.charCodeAt(0);
location.hash = "#" + key_code;
}
</script>
</body>
</html>
)";
m_webView->SetPage(s,"");
Bind(wxEVT_WEBVIEW_NAVIGATING,&MyFrame::OnWebViewNavigating, this);
m_webView->Bind(wxEVT_KEY_UP, &MyFrame::OnKeyUp, this);
}
void MyFrame::OnKeyUp(wxKeyEvent& event)
{
// Escape has keycode 69, so to check if it was pressed:
if ( event.GetKeyCode() == 69 )
{
// Change this to how you want to handle the escape key press.
SetTitle("Escape was pressed");
}
else
{
// Handle any other key presses here.
}
}
void MyFrame::OnWebViewNavigating(wxWebViewEvent& event)
{
wxKeyEvent keyEvent(wxEVT_KEY_UP);
keyEvent.SetEventObject(event.GetEventObject());
wxURI uri(event.GetURL());
uri.GetFragment().ToLong(&keyEvent.m_keyCode);
m_webView->ProcessWindowEvent(keyEvent);
// Veto the action since we don't actually want to navigate.
event.Veto();
}
class MyApp : public wxApp
{
public:
virtual bool OnInit()
{
MyFrame* frame = new MyFrame();
frame->Show();
return true;
}
};
wxIMPLEMENT_APP(MyApp);
It's a bit of a pain, but it's the best way we can connect the Java Script and wxWidgets worlds unless you want to run a webserver locally.

Related

Is it possible to programatically create a xaml page?

I might write no sense on the next lines:
I tried to derive a struct named mainpage from winrt::Windows::UI::Xaml::Controls::Page and pass it to winrt::xaml_typename<>(), in "<>" is mainpage.
It will be understandable when you look at the code:
Point number 1 "(1)" is the mainpage.h file, is very short.
Point number 2 "(2)" is the App.cpp file, it only has the necessary.
//(1) mainpage.h
#pragma once
#include "pch.h"
struct mainpage : winrt::Windows::UI::Xaml::Controls::Page
{
mainpage() {
winrt::Windows::UI::Xaml::Controls::Button thebutton = winrt::Windows::UI::Xaml::Controls::Button();
thebutton.Click([&](const IInspectable& sender, const winrt::Windows::UI::Xaml::RoutedEventArgs& event_arg)
{
thebutton.Content(winrt::box_value(L"Clicked"));
});
}
};
//(2) App.cpp
#include "pch.h"
#include "mainpage.h"
struct App : winrt::Windows::UI::Xaml::ApplicationT<App>
{
void OnLaunched(const winrt::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs& event_arg)
{
winrt::Windows::UI::Xaml::Controls::Frame root_frame{ nullptr };
winrt::Windows::UI::Xaml::UIElement content = winrt::Windows::UI::Xaml::Window::Current().Content();
if (content)
{
root_frame = content.try_as<winrt::Windows::UI::Xaml::Controls::Frame>();
}
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (root_frame == nullptr)
{
// Create a Frame to act as the navigation context and associate it with
// a SuspensionManager key
root_frame = winrt::Windows::UI::Xaml::Controls::Frame();
root_frame.NavigationFailed({ this, &App::OnNavigationFailed });
if (event_arg.PreviousExecutionState() == winrt::Windows::ApplicationModel::Activation::ApplicationExecutionState::Terminated)
{
// Restore the saved session state only when appropriate, scheduling the
// final launch steps after the restore is complete
}
if (event_arg.PrelaunchActivated() == false)
{
if (root_frame.Content() == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
root_frame.Navigate(winrt::xaml_typename<mainpage>(), box_value(event_arg.Arguments()));
}
// Place the frame in the current Window
winrt::Windows::UI::Xaml::Window::Current().Content(root_frame);
// Ensure the current window is active
winrt::Windows::UI::Xaml::Window::Current().Activate();
}
}
else
{
if (event_arg.PrelaunchActivated() == false)
{
if (root_frame.Content() == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
root_frame.Navigate(winrt::xaml_typename<mainpage>(), box_value(event_arg.Arguments()));
}
// Ensure the current window is active
winrt::Windows::UI::Xaml::Window::Current().Activate();
}
}
}
void App::OnNavigationFailed(const IInspectable&, const winrt::Windows::UI::Xaml::Navigation::NavigationFailedEventArgs& event_arg)
{
throw winrt::hresult_error(E_FAIL, winrt::hstring(L"Failed to load Page ") + event_arg.SourcePageType().Name);
}
};
int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
winrt::Windows::UI::Xaml::Application::Start([](auto &&) { winrt::make<App>(); });
}
If it is not possible, how can I properly create a page?
It is simple if you have installed the CppWinRT VSIX. Then create a "View model" and edit the files. You shouldn't derive the struct from the winrt::Windows::UI::Xaml::Controls::Page class because winrt::xaml_typename<> needs a WinRT class in <>.

Gtk.DrawingArea mouse events using Vala

I have been trying to receive mouse events on my Gtk.DrawingArea, using Vala, with no success. Specifically I am sub-classing Gtk.DrawingArea and in my constructor I add the events I want to receive:
this.add_events (Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK);
Then, in the same constructor below, I register signal handlers for these events:
this.enter_notify_event.connect (
(page, event) => {
stdout.printf("mouse entered !!! \n");
return true;
}
);
this.button_press_event.connect (
(page, event) => {
stdout.printf("mouse click \n");
return false;
}
);
I tried both return true and return false to check what happens in both cases. However I see no messages on the console when I move the pointer on the Gtk.DrawingArea or when I click on it. I even set the events for the top Gtk.Window:
this.set_events (this.get_events() |
Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK);
but the events don't seem to get received. What could be going wrong?
Your code seems correct although it's not a MVCE. I would point out the callback handlers prototype as being incorrect but since you're not using event data it should not be a "problem". The callback prototypes for enter_notify_event and button_press_eventonly supply the event, so the page argument it's incorrect.
Anyway, i tested with a very simple and raw code and it worked. Please verify:
using Gtk;
public class MyWidget : Gtk.DrawingArea {
public MyWidget () {
this.set_events (Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK);
this.enter_notify_event.connect ((event) => {
stdout.printf ("mouse entered !!! \n");
return false;
});
this.button_press_event.connect ((event) => {
stdout.printf("mouse click \n");
return false;
});
}
}
public void main (string[] args) {
Gtk.init (ref args);
var window = new Gtk.Window ();
window.add (new MyWidget ());
window.destroy.connect (Gtk.main_quit);
window.show_all ();
Gtk.main ();
}
Compile with valac test.vala --pgk gtk+-3.0.
The result is:
Using Vala 0.30.2 and Gtk+ 3.18 on Fedora 23.

Catch mouse event on tree widget item in QTreeWidget

In tree widget I have following signal connected:
connect(mTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem*, int)),
SLOT(onItemClicked(QTreeWidgetItem*, int)));
where onItemClicked() slot is following:
void WidgetBox::onItemClicked(QTreeWidgetItem *item, int )
{
int index = getPageIndex(item);
setCurrentIndex(index);
}
int WidgetBox::getPageIndex(QTreeWidgetItem *item)
{
if (!item) return -1;
QTreeWidgetItem *parent = item->parent();
if(parent) // Parent is top level item
{
return mTreeWidget->indexOfTopLevelItem(parent);
}
else // Current item is top level
{
return item->treeWidget()->indexOfTopLevelItem(item);
}
}
void WidgetBox::setCurrentIndex(int index)
{
if (index != currentIndex() && checkIndex(index))
{
mTreeWidget->setCurrentItem(mTreeWidget->topLevelItem(index));
emit currentIndexChanged(index);
}
}
However I can't catch itemClicked() signal and onItemClicked() never executed because top level items has push button widget (set with setItemWidget() method) which intercepts mouse event and child items contain container widgets which may have any widget combinations in them.
Is there a good method here to invoke this itemClicked() signal for both top level and child items of tree widget?
installEventFilter() for all widgets found in an item by something like following:QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>();?
Or establish mouse event propagation somehow?
QCoreApplication::postEvent()?
How to organize such process better so all widgets process mouse event as they need to and TreeWidget issue SIGNAL(itemClicked()) as well?
Full sources to reproduce: https://github.com/akontsevich/WidgetBox
So solution is simple and following - just re-send void itemClicked(QTreeWidgetItem *item, int column); signal in PageEventFilter:
PageEventFilter::PageEventFilter(QObject *parent, QTreeWidgetItem *item)
: QObject(parent)
, mItem(item)
{
connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
mItem->treeWidget(), SIGNAL(itemClicked(QTreeWidgetItem*,int)));
}
bool PageEventFilter::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress)
{
// Resend signal to QTreeWidget
emit itemClicked(mItem, 0);
return false; // Send event to the object (do not filter it)
}
else
{
// standard event processing
return QObject::eventFilter(obj, event);
}
}
P.S. Will leave previous answer as well if somebody needs code or idea.
Created event filter like this:
class PageEventFilter : public QObject
{
Q_OBJECT
public:
PageEventFilter(QObject *parent, QTreeWidgetItem *item);
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
QTreeWidgetItem *mItem;
};
bool PageEventFilter::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress)
{
// Emitate mouse event for parent QTreeWidget
QMouseEvent *oldEvent = (QMouseEvent *)event;
QRect itemRect = mItem->treeWidget()->visualItemRect(mItem);
QPointF mousePos(itemRect.x() + 1, itemRect.y() + 1);
QMouseEvent *newEvent = new QMouseEvent(oldEvent->type(),
mousePos,
oldEvent->button(),
oldEvent->buttons(),
oldEvent->modifiers());
QCoreApplication::postEvent(mItem->treeWidget(), newEvent);
return false; // Sent event to the object (do not filter it)
}
else
{
// standard event processing
return QObject::eventFilter(obj, event);
}
}
Install it to a button in tree widget item. It creates and sends (imitates) mouse event to tree widget, however tree widget still does not send itemClicked(QTreeWidgetItem*, int) signal. What is the problem could be? Wrong mouse pos? Tried to send event to viewport() - no luck as well. Any way to solve this?

Qt5 QNetworkAccessManager finished signal never emits

I have a very confusing problem.
I had a simple project that was downloading files from some ftp servers. It worked very good.
Then, I tried implementing that same code into a larger project (first one was a Console App, and the second one is GUI, but I don't think that changes anything..).
After doing some debugging it seems to me that finished() signal from QNetworkAccessManager somehow never gets emitted (or received).
Again, the exact same lines of code work as a separate project.
downloader.h
#ifndef DOWNLOADER_H
#define DOWNLOADER_H
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QFile>
#include <QDebug>
class Downloader : public QObject
{
Q_OBJECT
public:
explicit Downloader(QObject *parent = 0);
signals:
void dloadend();
void printed();
public slots:
void replyFinished (QNetworkReply *reply);
void doDownload(QUrl url);
void printDLend();
private:
QNetworkAccessManager *manager;
};
#endif // DOWNLOADER_H
downloader.cpp
#include "downloader.h"
Downloader::Downloader(QObject *parent) :
QObject(parent)
{
}
void Downloader::doDownload(QUrl url)
{
qDebug()<<"entry: doDownload\n";
QNetworkRequest req(url);
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),this,SLOT(printDLend()));//SLOT(replyFinished(QNetworkReply*)));
manager -> get(req);
qDebug()<<"exit: doDownload\n";
}
void Downloader::replyFinished (QNetworkReply *reply)
{
qDebug()<<"entry: reply\n";
if(reply->error()) {
qDebug() << "ERROR!";
qDebug() << reply->errorString();
}
else
{
qDebug() << "Download finished!";
QFile *file = new QFile("C:/users/jelicicm/Desktop/test1.hex");
if(file->open(QFile::Append))
{
file->write(reply->readAll());
file->flush(); file->close();
qDebug() <<"Downloaded file size:" <<file->size() <<"Bytes";
qDebug() <<"File name: "<< file->fileName();
;
}
delete file;
}
reply->deleteLater();
manager->deleteLater();
emit dloadend();
}
mainwindow.cpp (important part)
void MainWindow::on_actionDownloadFirmwareImage_triggered()
{
Downloader d;
QUrl url("ftp://ftp.xenbase.org/pub/Genomics/JGI/Xenla6.0/Xenla_6.0_JGI_Gene_Models.fasta.tgz");
qDebug() << "url, debug";
ui->plainTextEdit->appendPlainText(url.toDisplayString());
d.doDownload(url);
QObject::connect(&d,SIGNAL(dloadend()),this, SLOT(printDLend()));
}
Can't get my head around this.
Any help is welcome,
Thanks!
EDIT> More info:
Debugger posts this>
url, debug
entry: doDownload
exit: doDownload
You create object Downloader on stack and it is deleted right after your function exits. You must create object using new, and provide MainWindow object as parent, so after you close MainWindow, the object will be destroyed.
If the download finish, you still need to destroy the object, so simply connect the dloadend() signal to deleteLater() slot, Qt loop will delete your object right after all signal are processed.
void MainWindow::on_actionDownloadFirmwareImage_triggered()
{
Downloader *d = new Downloader(this);
QUrl url("ftp://example.com/some.file.tgz");
qDebug() << "url, debug";
ui->plainTextEdit->appendPlainText(url.toDisplayString());
d->doDownload(url);
QObject::connect(d,SIGNAL(dloadend()),this, SLOT(printDLend()));
QObject::connect(d,SIGNAL(dloadend()), d, SLOT(deleteLater()));
}

Pause application in QML when app is in background Symbian

I want to know of any pure QML way to find out whether the application is in the background or not and then accordingly stop or play music. In meego the alternate way to do is through the PlatformWindow Element but it does not exist in Symbian QML. Help needed please
Finally I got it working :) and i did it though Qt way... here are the steps
1) Create a class MyEventFilter
class myEventFilter : public QObject
{
bool eventFilter(QObject *obj, QEvent *event) {
switch(event->type()) {
case QEvent::WindowActivate:
emit qmlvisiblechange(true);
qDebug() << "Window activated";
bis_foreground=true;
return true;
case QEvent::WindowDeactivate:
emit qmlvisiblechange(false);
qDebug() << "Window deactivated";
bis_foreground=false;
return true;
default:
return false;
}
}
void dosomething();
private:
int something;
public:
bool bis_foreground;
Q_OBJECT
public slots:
Q_INVOKABLE QString checkvisibility() {
if (bis_foreground==true) return "true";
else return "false";
}
signals:
void qmlvisiblechange(bool is_foreground);
};
2) Then in main.cpp include this file include the class and add setContext propery like this
context->setContextProperty("myqmlobject", &ef);
3) in qml file call it like this:
Item {
id: name
Connections
{
target:myqmlobject
onQmlvisiblechange:
{
if(is_foreground)
{
//dont do anything...
}
else
{
playSound.stop()
}
}
}
}
Enjoy :)
Why do you need a pure QML way?
You can detect if an application has been sent to the background by installing an event filter.
Check: http://www.developer.nokia.com/Community/Wiki/Detecting_when_a_Qt_application_has_been_switched_to_the_background_and_when_resumed
For a "pure" QML way, there is the Symbian QML element:
http://doc.qt.nokia.com/qt-components-symbian/qml-symbian.html
It has a foreground property that indicates whether the app is in the foreground or in the background. You can try connecting to onForegroundChanged.
From the documentation, the Symbian element is not "creatable". It exists as a context property named symbian. So a sample usage would be:
import QtQuick 1.1
import com.nokia.symbian 1.1
PageStackWindow {
id: window
initialPage: MainPage {tools: toolBarLayout}
showStatusBar: true
showToolBar: true
function appForegroundChanged() {
console.log("Foreground: " + symbian.foreground)
}
function appCurrentTimeChanged() {
console.log("Current time: " + symbian.currentTime)
}
Component.onCompleted: {
symbian.currentTimeChanged.connect(appCurrentTimeChanged)
symbian.foregroundChanged.connect(appForegroundChanged)
}
ToolBarLayout {
id: toolBarLayout
ToolButton {
flat: true
iconSource: "toolbar-back"
onClicked: window.pageStack.depth <= 1 ? Qt.quit() : window.pageStack.pop()
}
}
}