Reputation: 326
I have two QWidgets inside a QHBoxLayout. I want to be able to change the width of the left QWidget by clicking on its right side and moving mouse (such as the Qt Editor's projects browser).
Upvotes: 1
Views: 1544
Reputation: 4050
You can do exactly what you want by using QSplitter. You can find a complete example here: https://stackoverflow.com/a/38433287/4297146
Upvotes: 3
Reputation: 4181
You can use eventFilter
and get mouse Move,Enter,Leave and mouse click on a widget.
Check this example:
I made two widget with QHBoxLayout
and get QEvent::HoverEnter
and QEvent::MouseButtonPress
for both.
.cpp file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
widgetOneW = 300;
widgetTwoW = 300;
ui->widgetOne->installEventFilter(this);
ui->widgetTwo->installEventFilter(this);
ui->widgetOne->setAttribute(Qt::WA_Hover);
ui->widgetTwo->setAttribute(Qt::WA_Hover);
}
bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
if ((object == ui->widgetOne) && (event->type() == QEvent::HoverEnter))
{
ui->widgetOne->resize(100, ui->widgetOne->height());
ui->widgetTwo->resize(widgetTwoW, ui->widgetTwo->height());
return true;
}
else if ((object == ui->widgetOne) && (event->type() == QEvent::MouseButtonPress))
{
QMouseEvent *keyEvent = static_cast<QMouseEvent *> (event);
if(keyEvent->button() == Qt::LeftButton)
{
ui->widgetOne->resize(100, ui->widgetOne->height());
ui->widgetTwo->resize(widgetTwoW, ui->widgetTwo->height());
return true;
}
}
else if ((object == ui->widgetTwo) && (event->type() == QEvent::HoverEnter))
{
ui->widgetOne->resize(widgetOneW, ui->widgetOne->height());
ui->widgetTwo->resize(100, ui->widgetTwo->height());
return true;
}
else if ((object == ui->widgetTwo) && (event->type() == QEvent::MouseButtonPress))
{
QMouseEvent *keyEvent = static_cast<QMouseEvent *> (event);
if(keyEvent->button() == Qt::LeftButton)
{
ui->widgetOne->resize(widgetOneW, ui->widgetOne->height());
ui->widgetTwo->resize(100, ui->widgetTwo->height());
}
}
}
MainWindow::~MainWindow()
{
delete ui;
}
.h file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QKeyEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
int widgetOneW;
int widgetTwoW;
public slots:
bool eventFilter(QObject *object, QEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
.pro file:
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = first
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
Upvotes: 0