QWidget can we get/modify existing context menu of a widget - qt

I have third party widget which provides me some context menu. Lets say cut, copy paste, select all.
Now I just want to modify only the paste functionality of the existing context menu. I know that I can implement whole context menu from scratch in the contextMenuEvent. But I do not want to do that as I am satisfied with other context menu actions, and just want to modify only the paste functionality.
I am using QT 4.8 on Mac OSX.
If such a thing is not possible at the moment can someone give me link/reference for that ? So that I can satisfy my stakeholders.
Edit: To be more clearer on what I am trying to do is, disable the paste context menu for some reason, and want to enable it later on depending on the situation/events.

I'm not sure that it can be done in a common way.
Here is a tricky solution:
In contextMenuEvent create a queued call to some slot:
QMetaObject::invokeMethod(this, "patchMenu", Qt::QueuedConnection);
Get visible windows in the slot and find QMenu. Get actions out of it and enable/disable them:
Q_SLOT patchMenu()
{
QWidgetList widgets = QApplication::topLevelWidgets();
foreach (QWidget* widget, widgets)
{
if (QMenu* menu = qobject_cast<QMenu*>(widget))
{
QList<QAction*> actions = menu->actions();
// here you can either get an action by index actions[5]
// or search the action by text
actions;
}
}
}
EDIT:
Here is a working example which demonstrates this approach:
window.h
#pragma once
#include <QtGui>
class Window: public QMainWindow
{
Q_OBJECT
public:
Window(QWidget *parent = 0);
};
class A : public QWidget
{
public:
virtual void contextMenuEvent(QContextMenuEvent* e);
};
class B : public A
{
Q_OBJECT;
public:
virtual void contextMenuEvent(QContextMenuEvent*);
Q_SLOT void patchMenu();
};
window.cpp
#include "window.h"
Window::Window(QWidget *parent) : QMainWindow(parent)
{
setCentralWidget(new B());
}
void B::patchMenu()
{
QWidgetList widgets = QApplication::topLevelWidgets();
foreach (QWidget* widget, widgets)
{
if (QMenu* menu = qobject_cast<QMenu*>(widget))
{
QList<QAction*> actions = menu->actions();
// here you can either get an action by index actions[5]
// or search the action by text
actions;
}
}
}
void B::contextMenuEvent(QContextMenuEvent* e)
{
QMetaObject::invokeMethod(this, "patchMenu", Qt::QueuedConnection);
A::contextMenuEvent(e);
}
void A::contextMenuEvent(QContextMenuEvent* e)
{
QMenu menu;
QAction* action = new QAction(QIcon(), "text", &menu);
menu.addAction(action);
menu.exec(e->globalPos());
}

Related

Identifying which label was clicked in qt

I have 10 Qlabels with an image on each. When i click on a label, its image should be cleared. I am able to identify which label was clicked theorotically, using the pixel clicked and size of each image. But how to use that information?
Eg. each label has dimension 100*100, the first label starting from 0,0. if pixel clicked is 250,50, i know that the third label was clicked, but how to use this to clear the label.
Im stuck.
There are a few ways how to implement it.
First. I would recommend to use a new class that inherits QLabel and overloads mouseReleaseEvent() handler where you just call clear() method. In this case the label will detect the mouse clicks itself and will clear its content internally.
class SelfClearingLabel : public QLabel
{
public:
using QLabel::QLabel;
protected:
void mouseReleaseEvent(QMouseEvent * event)
{
if (event->button()==Qt::LeftButton)
// process only clicks on the left button
{
clear();
}
QLabel::mouseReleaseEvent(event);
}
};
Second. You can catch mouseReleaseEvent() in your top widget and iterate over all of your child QLabel widgets and check which one is currently under mouse and clear the one. If you have other labels on this widget that shouldn't be cleared on mouse clicks then you can add some property to the QLabels that are under your interest.
void SomeTopFrame::createImageLabels(int count)
{
for (int i=0;i<count;i++)
{
QLabel* label=new QLabel(this);
label->setProperty("clear_on_click",true);
// assume that labels are added to layout *m_labelsLayout;
m_labelsLayout->addWidget(label);
}
}
void SomeTopFrame::mouseReleaseEvent(QMouseEvent * event)
{
if (event->button()==Qt::LeftButton)
// process only clicks on the left button
{
QList<QLabel*> labels=findChildren<QLabel*>();
foreach (QLabel* label, labels)
{
if (label->property("clear_on_click")&&label->underMouse())
{
label->clear();
break;
}
}
}
QFrame::mouseReleaseEvent(event);
}
It is a sample code just to show the principle. In production you can add a check that mouseReleaseEvent() is on the same widget as the mousePressEvent() to avoid triggering on drag and drop events.
Create the custom class that inherit QLabel :
ClickableLabel.h
class ClickableLabel : public QLabel
{
Q_OBJECT
public:
explicit ClickableLabel( const QString& text="", QWidget* parent=0 );
~ClickableLabel();
signals:
void clicked();
protected:
void mousePressEvent(QMouseEvent* event);
};
ClickableLabel.cpp
ClickableLabel::ClickableLabel(const QString& text, QWidget* parent)
: QLabel(parent)
{
setText(text);
}
ClickableLabel::~ClickableLabel()
{
}
void ClickableLabel::mousePressEvent(QMouseEvent* event)
{
emit clicked();
}
Just connect all labels clicked signal to following slot :
MyClass::labelClicked()
{
ClickableLabel *label = (ClickableLabel*)QObject::sender;
if(label)
label->clear();
}

Office like QToolButton

I currently try to make a QToolButton looks like equivalent in Office.
It should look like this:
I know I can access menu button with QToolButton::menu-button, but QToolButton::menu-button:hover is same as QToolButton:hover so I can't differ between both and I can't set a border just for QToolButton::menu-button. Any idea?
You can create something like split button.
class SplitButton : public QPushButton
{
Q_OBJECT
public:
explicit SplitButton(QWidget *parent = 0);
void setMenu(QMenu* menu);
protected:
void resizeEvent ( QResizeEvent * );
void mousePressEvent ( QMouseEvent * );
private:
QFrame* line;
};
Added opportunity to insert menu by setMenu() method. QFrame is needed for separating button and popup menu.
At constructor just initialize base class:
#include <QFrame>
#include <QMenu>
#include <QResizeEvent>
SplitButton::SplitButton(QWidget *parent):
QPushButton(parent)
{
}
Popup menu will be added like this:
void SplitButton::setMenu( QMenu* menu )
{
if (menu) {
line = new QFrame(this);
line->setFrameShape(QFrame::VLine);
line->setFrameShadow(QFrame::Sunken);
QPushButton::setMenu(menu);
connect(menu, &QMenu::triggered, [=](QAction *act) {
setText(act->text());
});
}
}
As you can see we used QPushButton::setMenu() method and connect menu triggered signal to slot, realized with labda, so you need include c++11 compatibility.
After we need to override resize, mousePress and keyPressed events. As minimal exmaple i done second ones.
void SplitButton::resizeEvent ( QResizeEvent * event )
{
if (menu()) {
int width = event->size().width();
int height = event->size().height();
line->setGeometry(QRect(width - 18, 4, 3, height - 8));
}
}
At resize event if menu is available we add frame by offset for pseudo-button.
void SplitButton::mousePressEvent( QMouseEvent * event )
{
if (menu()) {
if ( width()-event->x() <= 15 )
showMenu();
else
setDown(true);
} else {
QPushButton::mousePressEvent(event);
}
}
For mousePress event we just select what we want to do: show menu or push button.
Usage:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), m_file(QString())
{
setupUi(this);
SplitButton *split = new SplitButton;
split->setText("B");
QMenu *menu = new QMenu;
menu->addAction("Y");
menu->addAction("B");
menu->addAction("U");
split->setMenu(menu);
split->setCheckable(true);
Ui::MainWindow::mainToolBar->addWidget(split);
}
And you can set button chechable for Office-like effects.
It's just one of possible ways to realize this, I hope it will be helpful for you.
It look like on screen for me:
Of cource, it is not final result, you need repaint it like you want or use styles for flat-style.

Toggle A QAction To Set QStackedWidget's Current Widget

So what I am trying to do is when I press the showMenu (QAction), the container (QStackedWidget) changes the current widget to menuWidget AND when I press it again it hides.
Ok so I have managed to get this code:
connect(showMenu, SIGNAL(triggered()), map, SLOT(map()));
map->setMapping(menuWidget, container);
Object::connect(map, SIGNAL(mapped(QWidget *)), container, SLOT(setCurrentWidget(QWidget *)));
also if I run:
container->setCurrentWidget(menuWidget);
directly, it works fine, so I have not messed up in that way.
You should create a slot in your class where you show/hide menuWidget.
If you are using a checkable QAction object, then you can use QAction::toggled(bool checked) signal, and use the checked variable to determine if you should show or hide your widget.
If you're not using a checkable QAction object, then you should create a class member variable of type bool that you toggle in your slot:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
...
private:
bool toggleStatus; // set this to false in your constructor
...
};
 
void MainWindow::menuToggled()
{
toggleStatus = !toggleStatus;
if(toggleStatus)
{
container->setCurrentWidget(menuWidget);
}
else
{
container->setCurrentWidget(mdiContainer);
}
}

show onscreenkeyboard when type in QLineEdit in Qt

I want to show osk.exe(onscreenkeyboard) when click on the QLineEdit and when focus out osk.exe hide or minimized?
how can i do?
thanks
You need to use a QProcess and reimplement the methods QLineEdit::focusInEvent and QLineEdit::focusOutEvent. Try implement a class inheriting from QLineEdit like this:
#include <QLineEdit>
#include <QProcess>
class MyLineEdit: public QLineEdit
{
public:
MyLineEdit(QWidget * parent = 0): QLineEdit(parent)
{
process_ = new QProcess();
}
protected:
void focusInEvent(QFocusEvent * e)
{
QLineEdit::focusInEvent(e);
process_->start("start C:\\osk.exe");
}
void focusOutEvent(QFocusEvent * e)
{
QLineEdit::focusOutEvent(e);
process_->kill();
}
private:
QProcess * process_;
}
(Of course replace C:\\osk.exe by the exact address of this osk.exe).
Then just use a MyLineEdit instead of a QLineEdit, it should work. I do not know how to hide or minimize the process, so I decided to kill it and restart it if necessary instead ;-)

How to change a parent widget's background when a child widget has focus?

I would like to highlight a QFrame, if one of it's child widgets has focus (so the users know where to look for the cursor ;-)
using something along
ui->frame->setFocusPolicy(Qt::StrongFocus);
ui->frame->setStyleSheet("QFrame:focus {background-color: #FFFFCC;}");
highlights the QFrame when I click on it, but it loses its focus once one of its child widgets is selected.
Possible approaches:
I could connect() QApplication::focusChanged(old,now) and check each new object if it is a child of my QFrame, but this gets messy.
I could also subclass each child widget and reimplement focusInEvent()/focusOutEvent() and react on that, but with a lot of different widgets, this is also a lot of work.
Is there a more elegant solution?
Well, you can extend QFrame to make it listen on focus change of its children widgets.
Or you can also install an event filter on children widgets to catch QFocusEvent.
Here is an example:
MyFrame.h
#ifndef MYFRAME_H
#define MYFRAME_H
#include <QFrame>
class MyFrame : public QFrame
{
Q_OBJECT
public:
explicit MyFrame(QWidget* parent = 0, Qt::WindowFlags f = 0);
void hookChildrenWidgetsFocus();
protected:
bool eventFilter(QObject *object, QEvent *event);
private:
QString m_originalStyleSheet;
};
#endif // MYFRAME_H
MyFrame.cpp
#include <QEvent>
#include "MyFrame.h"
MyFrame::MyFrame(QWidget *parent, Qt::WindowFlags f)
: QFrame(parent, f)
{
m_originalStyleSheet = styleSheet();
}
void MyFrame::hookChildrenWidgetsFocus()
{
foreach (QObject *child, children()) {
if (child->isWidgetType()) {
child->installEventFilter(this);
}
}
}
bool MyFrame::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn) {
setStyleSheet("background-color: #FFFFCC;");
} else if (event->type() == QEvent::FocusOut) {
setStyleSheet(m_originalStyleSheet);
}
return QObject::eventFilter(object, event);
}
MainWindow.cpp
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include "MyFrame.h"
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setWindowTitle(tr("Test"));
MyFrame *frame1 = new MyFrame(this);
frame1->setLayout(new QVBoxLayout());
frame1->layout()->addWidget(new QLineEdit());
frame1->layout()->addWidget(new QLineEdit());
frame1->layout()->addWidget(new QLineEdit());
frame1->hookChildrenWidgetsFocus();
MyFrame *frame2 = new MyFrame(this);
frame2->setLayout(new QVBoxLayout());
frame2->layout()->addWidget(new QLineEdit());
frame2->layout()->addWidget(new QLineEdit());
frame2->layout()->addWidget(new QLineEdit());
frame2->hookChildrenWidgetsFocus();
QHBoxLayout *centralLayout = new QHBoxLayout();
centralLayout->addWidget(frame1);
centralLayout->addWidget(frame2);
QWidget *centralWidget = new QWidget();
centralWidget->setLayout(centralLayout);
setCentralWidget(centralWidget);
}
I believe the both answers you were given are wrong. They work for simple cases but are extremely fragile and clumsy. I believe that the best solution is what you actually suggested in your question. I would go for connecting to QApplication::focusChanged(from, to). You simply connect your main frame object to this signal and in the slot you check if the to object (the one which received focus) is a child of your frame object.
Frame::Frame(...)
{
// ...
connect(qApp, &QApplication::focusChanged, this, &Frame::onFocusChanged);
// ...
}
// a private method of your Frame object
void Frame::onFocusChanged(QWidget *from, QWidget *to)
{
auto w = to;
while (w != nullptr && w != this)
w = w->parentWidget();
if (w == this) // a child (or self) is focused
setStylesheet(highlightedStylesheet);
else // something else is focused
setStylesheet(normalStylesheet);
}
The advantage is obvious. This code is short and clean. You connect only one signal-slot, you do not need to catch and handle events. It responds well to any layout changes done after the object is created. And if you want to optimize away unnecessary redrawing, you should cache the information whether any child is focused and change the stylesheet only and only if this cached value gets changed. Then the solution would be prefect.
First, create a simple subclass of QFrame which reimplements the eventFilter(QObject*, QEvent*) virtual function:
class MyFrame : public QFrame {
Q_OBJECT
public:
MyFrame(QWidget *parent = 0, Qt::WindowFlags f = 0);
~MyFrame();
virtual bool eventFilter(QObject *watched, QEvent *event);
};
Use MyFrame instead of QFrame to contain your widgets. Then, somewhere in your code where you create the widgets contained in MyFrame, install an event filter on those widgets:
// ...
m_myFrame = new MyFrame(parentWidget);
QVBoxLayout *layout = new QVBoxLayout(myFrame);
m_button = new QPushButton("Widget 1", myFrame);
layout->addWidget(m_button);
m_button->installEventFilter(myFrame);
//...
At that point, MyFrame::eventFilter() will be called before any event is delivered to the widget, letting you act on it before the widget is aware of it. Within MyFrame::eventFilter(), return true if you want to filter the event out (i.e. you don't want the widget to process the event), or return false otherwise.
bool MyFrame::eventFilter(QObject *watched, QEvent *event)
{
if (watched == m_button) { // An event occured on m_button
switch (event -> type()) {
case QEvent::FocusIn:
// Change the stylesheet of the frame
break;
case QEvent::FocusOut:
// Change the stylesheet back
break;
default:
break;
}
}
return false; // We always want the event to propagate, so always return false
}

Resources