Qt Hide Taskbar Item - qt

I have a custom QWidget and I simple don't want it to show up in the taskbar. I have a QSystemTrayIcon for managing exiting/minimizing etc.

I think the only thing you need here is some sort of parent placeholder widget. If you create your widget without a parent it is considered a top level window. But if you create it as a child of a top level window it is considered a child window und doesn't get a taskbar entry per se. The parent window, on the other hand, also doesn't get a taskbar entry because you never set it visible: This code here works for me:
class MyWindowWidget : public QWidget
{
public:
MyWindowWidget(QWidget *parent)
: QWidget(parent, Qt::Dialog)
{
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
MyWindowWidget widget(&window);
widget.show();
return app.exec();
}
No taskbar entry is ever shown, if this is want you intended.

Just set Qt::SubWindow flag for widget.

If you want to show/hide the widget without ever showing it at the taskbar your might check the windowflags of that widget. I'm not 100% sure, but I think I used Qt::Dialog | Qt::Tool and Qt::CustomizeWindowHint to achieve this, but my window wasn't fully decorated too. Another thing you might keep in mind if you play with that is the exit policy of your application. Closing/Hiding the last toplevel-window will normally exit your application, so maybe you need to call QApplication::setQuitOnLastWindowClosed(false) to prevent that...

Python code to achive this:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent, Qt.Tool)
window = MainWindow()
window.show()

Related

Can't use setWindowsFlag when set parent to Qdialog

I have QDialog which is a child of mainWindow. My problem is I can't use setWindowsFlag when set parent for the dialog: the dialog sticks to the top left of MainWindow and is transparent .The code look like this:
mainWindow::MainWindow(QWidget* parent): QMainWindow(parent)
{
this->setWindowsFlags(Qt::FramelessWindowHint);
mpConfirmDialog = new ConfirmDialog();//mpConfirmDialog is a pointer and member of MainWindow
mpConfirmDialog->setParent(ui->centralWidget) ;//pass ui->centralWidget in constructor cause crash when exit????
mpConfirmDialog->hide();
}
In constructor of ConfirmDialog:
ConfirmDialog::ConfirmDialog(QWidget* parent){
this->setWindowsFlags(Qt::FramelessWindowHint);// only effective if comment mpConfirmDialog->setParent(ui->centralWidget) in MainWindow
}
Any ideas are appreciated.
There is some inconsistency between OSes but we should keep in mind that the parent class constructor very likely sets some flags already and the flag add logic is bitwise OR. We can try to ensure we don't loose those flags.
this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);
This may help to degree but of course I don't have your environment and entire code sample to prove.

Hide QLineEdit blinking cursor

I am working on QT v5.2
I need to hide the blinking cursor (caret) of QLineEdit permanently.
But at the same time, I want the QLineEdit to be editable (so readOnly and/or setting editable false is not an option for me).
I am already changing the Background color of the QLineEdit when it is in focus, so I will know which QLineEdit widget is getting edited.
For my requirement, cursor (the blinking text cursor) display should not be there.
I have tried styleSheets, but I can't get the cursor hidden ( {color:transparent; text-shadow:0px 0px 0px black;} )
Can someone please let me know how can I achieve this?
There is no standard way to do that, but you can use setReadOnly method which hides the cursor. When you call this method it disables processing of keys so you'll need to force it.
Inherit from QLineEdit and reimplement keyPressEvent.
LineEdit::LineEdit(QWidget* parent)
: QLineEdit(parent)
{
setReadOnly(true);
}
void LineEdit::keyPressEvent(QKeyEvent* e)
{
setReadOnly(false);
__super::keyPressEvent(e);
setReadOnly(true);
}
As a workaround you can create a single line QTextEdit and set the width of the cursor to zero by setCursorWidth.
For a single line QTextEdit you should subclass QTextEdit and do the following:
Disable word wrap.
Disable the scroll bars (AlwaysOff).
setTabChangesFocus(true).
Set the sizePolicy to (QSizePolicy::Expanding, QSizePolicy::Fixed)
Reimplement keyPressEvent() to ignore the event when Enter/Return is hit
Reimplement sizeHint to return size depending on the font.
The implementation is :
#include <QTextEdit>
#include <QKeyEvent>
#include <QStyleOption>
#include <QApplication>
class TextEdit : public QTextEdit
{
public:
TextEdit()
{
setTabChangesFocus(true);
setWordWrapMode(QTextOption::NoWrap);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setFixedHeight(sizeHint().height());
}
void keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
event->ignore();
else
QTextEdit::keyPressEvent(event);
}
QSize sizeHint() const
{
QFontMetrics fm(font());
int h = qMax(fm.height(), 14) + 4;
int w = fm.width(QLatin1Char('x')) * 17 + 4;
QStyleOptionFrameV2 opt;
opt.initFrom(this);
return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
expandedTo(QApplication::globalStrut()), this));
}
};
Now you can create an instance of TextEdit and set the cursor width to zero :
textEdit->setCursorWidth(0);
Most straight forward thing I found was stolen from this github repo:
https://github.com/igogo/qt5noblink/blob/master/qt5noblink.cpp
Basically you just want to disable the internal "blink timer" Qt thinks is somehow good UX (hint blinking cursors never were good UX and never will be - maybe try color or highlighting there eh design peeps).
So the code is pretty simple:
from PyQt5 import QtGui
app = QtGui.QApplication.instance()
app.setCursorFlashTime(0)
voilĂ .
Solution in python:
# somelibraries
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.setFocus() # this is what you need!!!
container = QWidget()
container.setLayout(self.layout)
# Set the central widget of the Window.
self.setCentralWidget(container)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
I ran into the same problem but setReadOnly is not a viable option because it alters the UI behavior in other places too.
Somewhere in a Qt-forum I found the following solution that actually solves the problem exactly where it occurs without having impact on other parts.
In the first step you need to derive from QProxyStyle and overwrite the pixelMetric member function:
class CustomLineEditProxyStyle : public QProxyStyle
{
public:
virtual int pixelMetric(PixelMetric metric, const QStyleOption* option = 0, const QWidget* widget = 0) const
{
if (metric == QStyle::PM_TextCursorWidth)
return 0;
return QProxyStyle::pixelMetric(metric, option, widget);
}
};
The custom function simply handles QStyle::PM_TextCursorWidth and forwards otherwise.
In your custom LineEdit class constructor you can then use the new Style like this:
m_pCustomLineEditStyle = new CustomLineEditProxyStyle();
setStyle(m_pCustomLineEditStyle);
And don't forget to delete it in the destructor since the ownership of the style is not transferred (see documentation). You can, of course, hand the style form outside to your LineEdit instance if you wish.
Don't get complicated:
In QtDesigner ,
1.Go the the lineEdit 's property tab
2.Change focusPolicy to ClickFocus
That's it...

QPushButton Main Gui

I'm beginning with Qt and I do not understand something. Here is my code:
#include <QApplication>
#include <QtWebKitWidgets/QWebView>
#include <QMainWindow>
#include <QPushButton>
QApplication a(argc, argv);
QMainWindow *mWin = new QMainWindow();
QPushButton *button = new QPushButton("Button");
button->setGeometry(0,0,128,56);
button->show();
mWin->setGeometry(QRect(300,300,1024,640));
mWin->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
mWin->show();
return a.exec();
When I launch the program, it makes a pushbutton, but not on the main GUI. It instead makes it in the upper lefthand corner of my scoeen. How do I make the pushbutton part of the main GUI?
Both QMainWindow and QPushButton derive from QWidget and generally, QWidgets can display themselves independently, so don't need to be attached to a parent, though it's likely you'll want to group and organise the widgets you're presenting to the user.
For a beginner, I think that QMainWindow is a bit misleading as you don't actually need it to display widgets. If, for example, you wanted to just display the button, you only need create the QPushButton and call show: -
QPushButton pButton = new QPushButton("Test");
pButton->show();
Though it's rare that you'll actually want to do this. In actuality, though it appears pointless, you can even just create a QWidget and display that: -
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
w.show();
return a.exec();
}
The QWidget can now be the parent to all other widgets, still without you defining a QMainWindow.
It is likely that you will want other widgets to display and Qt uses a parent / child hierarchy system of linking them together. Amongst other things, an advantage here is that you don't need to keep track of the different widgets in order to release their memory. When you're finished, you just delete the top level item, which may be a QMainWidget, or QDialog or other QWidget based object. In the case of Windows, all you need to do is close them and their children are cleaned up too.
Adding Widgets to a QMainWindow can be done in different ways, depending upon what you're trying to achieve. Eventually, you'll likely want to use layouts that allow grouping of widgets in logical arrangements, but to start with, if you look at the constructor of the QPushButton, you'll see that it takes an optional parameter of QWidget* : -
QPushButton(QWidget * parent = 0)
This allows you to attach the widget you're creating (QPushButton in this case) to a parent. Therefore, create the QMainWindow and then pass its pointer to the QPushButton.
QMainWindow* pWindow = new QMainWindow; // create the main window
QPushButton pButton = new QPushButton(pWindow); // create the push button
pWindow->show(); // Display the main window and its children.
You're creating a button and a window, but you're not associating them together. Therefore, the button is not part of the main UI. In order to add the button to the main window, you should add the following line-
mWin->setCentralWidget(button);
When creating user interfaces with Qt, it's better to avoid setting the geometry explicitly. Here is a nice page which describes the layouting in Qt.
Also, you seem to be missing a main function.
You are not setting parent child relationship, you need QPushbutton as a child of QMainwindow. Then you can see QPushbutton on QMainwindow.
Please try this, I am not sure what exactly you want to achive..but below code will give some hind about how to proceed..
QApplication a(argc, argv);
QMainWindow *mWin = new QMainWindow();
QPushButton *button = new QPushButton(mWin); // setting parent as QMainwindow
button->setGeometry(0,0,128,56);
// button->show();
//mWin->setCentralWidget( button );
mWin->setGeometry(QRect(300,300,1024,640));
mWin->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
mWin->show()
;
Create a central widget for the main window and then use a layout to place the push button on the central widget. For example:
QMainWindow *mWin = new QMainWindow();
// Place the button in a layout
QHBoxLayout *layout = new QHBoxLayout;
QPushButton *button = new QPushButton("Button");
layout->addWidget(button);
// Set up a central widget for the main window
QWidget *centralWidget = new QWidget();
centralWidget->setLayout(layout);
mWin->setCentralWidget(centralWidget);
If you've placed your button into a layout this way (or as a central widget itself, as one of the other answers has indicated), you don't need to set the geometry on the button, nor do you need to call setVisible or show on the button explicitly (but you still need to on the main window).
Consider looking through some of Qt's examples, such as the application example for more information.

How to make a Qt widget invisible without changing the position of the other Qt widgets?

I've got a window full of QPushButtons and QLabels and various other fun QWidgets, all layed out dynamically using various QLayout objects... and what I'd like to do is occasionally make some of those widgets become invisible. That is, the invisible widgets would still take up their normal space in the window's layout, but they wouldn't be rendered: instead, the user would just see the window's background color in the widget's rectangle/area.
hide() and/or setVisible(false) won't do the trick because they cause the widget to be removed from the layout entirely, allowing other widgets to expand to take up the "newly available" space; an effect that I want to avoid.
I suppose I could make a subclass of every QWidget type that override paintEvent() (and mousePressEvent() and etc) to be a no-op (when appropriate), but I'd prefer a solution that doesn't require me to create three dozen different QWidget subclasses.
This problem was solved in Qt 5.2. The cute solution is:
QSizePolicy sp_retain = widget->sizePolicy();
sp_retain.setRetainSizeWhenHidden(true);
widget->setSizePolicy(sp_retain);
http://doc.qt.io/qt-5/qsizepolicy.html#setRetainSizeWhenHidden
The only decent way I know of is to attach an event filter to the widget, and filter out repaint events. It will work no matter how complex the widget is - it can have child widgets.
Below is a complete stand-alone example. It comes with some caveats, though, and would need further development to make it complete. Only the paint event is overridden, thus you can still interact with the widget, you just won't see any effects.
Mouse clicks, mouse enter/leave events, focus events, etc. will still get to the widget. If the widget depends on certain things being done upon an a repaint, perhaps due to an update() triggered upon those events, there may be trouble.
At a minimum you'd need a case statement to block more events -- say mouse move and click events. Handling focus is a concern: you'd need to move focus over to the next widget in the chain should the widget be hidden while it's focused, and whenever it'd reacquire focus.
The mouse tracking poses some concerns too, you'd want to pretend that the widget lost mouse tracking if it was tracking before. Properly emulating this would require some research, I don't know off the top of my head what is the exact mouse tracking event protocol that Qt presents to the widgets.
//main.cpp
#include <QEvent>
#include <QPaintEvent>
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QDialogButtonBox>
#include <QApplication>
class Hider : public QObject
{
Q_OBJECT
public:
Hider(QObject * parent = 0) : QObject(parent) {}
bool eventFilter(QObject *, QEvent * ev) {
return ev->type() == QEvent::Paint;
}
void hide(QWidget * w) {
w->installEventFilter(this);
w->update();
}
void unhide(QWidget * w) {
w->removeEventFilter(this);
w->update();
}
Q_SLOT void hideWidget()
{
QObject * s = sender();
if (s->isWidgetType()) { hide(qobject_cast<QWidget*>(s)); }
}
};
class Window : public QWidget
{
Q_OBJECT
Hider m_hider;
QDialogButtonBox m_buttons;
QWidget * m_widget;
Q_SLOT void on_hide_clicked() { m_hider.hide(m_widget); }
Q_SLOT void on_show_clicked() { m_hider.unhide(m_widget); }
public:
Window() {
QGridLayout * lt = new QGridLayout(this);
lt->addWidget(new QLabel("label1"), 0, 0);
lt->addWidget(m_widget = new QLabel("hiding label2"), 0, 1);
lt->addWidget(new QLabel("label3"), 0, 2);
lt->addWidget(&m_buttons, 1, 0, 1, 3);
QWidget * b;
b = m_buttons.addButton("&Hide", QDialogButtonBox::ActionRole);
b->setObjectName("hide");
b = m_buttons.addButton("&Show", QDialogButtonBox::ActionRole);
b->setObjectName("show");
b = m_buttons.addButton("Hide &Self", QDialogButtonBox::ActionRole);
connect(b, SIGNAL(clicked()), &m_hider, SLOT(hideWidget()));
QMetaObject::connectSlotsByName(this);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Window w;
w.show();
return a.exec();
}
#include "main.moc"
You can use a QStackedWidget. Put your button on the first page, a blank QWidget on the second, and change the page index to make your button vanish while retaining its original space.
I've 3 solutions in my mind:
1) Subclass your QWidget and use a special/own setVisible() replacement method witch turns on/off the painting of the widget (if the widget should be invisible simply ignore the painting with an overridden paintEvent() method). This is a dirty solution, don't use it if you can do it other ways.
2) Use a QSpacerItem as a placeholder and set it's visibility to the opposite of the QWidget you want to hide but preserve it's position+size in the layout.
3) You can use a special container widget (inherit from QWidget) which gets/synchronizes it's size based on it's child/children widgets' size.
I had a similar problem and I ended up putting a spacer next to my control with a size of 0 in the dimension I cared about and an Expanding sizeType. Then I marked the control itself with an Expanding sizeType and set its stretch to 1. That way, when it's visible it takes priority over the spacer, but when it's invisible the spacer expands to fill the space normally occupied by the control.
May be QWidget::setWindowOpacity(0.0) is what you want? But this method doesn't work everywhere.
One option is to implement a new subclass of QWidgetItem that always returns false for QLayoutItem::isEmpty. I suspect that will work due to Qt's QLayout example subclass documentation:
We ignore QLayoutItem::isEmpty(); this means that the layout will treat hidden widgets as visible.
However, you may find that adding items to your layout is a little annoying that way. In particular, I'm not sure you can easily specify layouts in UI files if you were to do it that way.
Here's a PyQt version of the C++ Hider class from Kuba Ober's answer.
class Hider(QObject):
"""
Hides a widget by blocking its paint event. This is useful if a
widget is in a layout that you do not want to change when the
widget is hidden.
"""
def __init__(self, parent=None):
super(Hider, self).__init__(parent)
def eventFilter(self, obj, ev):
return ev.type() == QEvent.Paint
def hide(self, widget):
widget.installEventFilter(self)
widget.update()
def unhide(self, widget):
widget.removeEventFilter(self)
widget.update()
def hideWidget(self, sender):
if sender.isWidgetType():
self.hide(sender)
I believe you could use a QFrame as a wrapper. Although there might be a better idea.
Try void QWidget::erase (). It works on Qt 3.

Qt/win: showMaximized() overlapping taskbar on a frameless window

I'm building an Qt-Application without the default window border as a frameless window.
The window functions are included by setting window flags in the QMainWindow like:
MainDialog::MainDialog(QWidget *parent):
QMainWindow(parent), currentProject(NULL), currentUser(NULL),
aViews(new QList<AViewForm*>()),
bViews(new QList<BViewForm*>()),
cViews(new QList<CViewForm*>())
{
ui.setupUi(this);
this->statusBar()->showMessage(tr(""));
this->setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowSystemMenuHint);
...
}
The MainWindow has an .ui file within, thats why I cannot inherit from QDesktopWidget.
The Problem I have now is that the Appication overlays the windows taskbar when maximizing.
My Question now: is there any posibility to find out the available height of the OS desktop without the
availableGeometry().height()
-Method of QDesktopWidget? I cannot find anything in the documentation :(
Somebody else here asked a similar Question but used a QWidget instead of a QMainWindow.
I would be glad about any hints to my Problem
As you say you can use QDesktopWidget. If you don't have your class inherit from it you can create one in your constructor just for retrieving the height :
QDesktopWidget w;
int availableHeight = w.availableGeometry().height();
Guess thats not good practise, but i solved it as followed:
I built a new class which needs a MainWindow as param and with slots for the scaling actions:
FullScreen::FullScreen(QMainWindow &mainWindow, QObject *parent) : QObject(parent), mainWindow(mainWindow)
{
this->saveCurrentPosition();
}
void FullScreen::maximize()
{
this->saveCurrentPosition();
mainWindow.move(QApplication::desktop()->mapToGlobal(QApplication::desktop()->availableGeometry().topLeft()));
mainWindow.resize(QApplication::desktop()->availableGeometry().size());
}
void FullScreen::normalize()
{
mainWindow.move(lastGlobalPosition);
mainWindow.resize(lastSize);
}
void FullScreen::saveCurrentPosition()
{
lastGlobalPosition = mainWindow.mapToGlobal(mainWindow.rect().topLeft());
lastSize = mainWindow.size();
}
The only Problem which now occures is when the application is fullscreen and you move the taskbar. I have not set any resizeEvent though

Resources