Layout mismanagement issue in Qt Application - c++

I have an application which shows some images in a grid and rest of the widgets in their respective positions. Something like this
Drawing inspiration from this i managed to solve keeping the aspect ratio of an image while resizing.
What are the issues:
The QLabel widgets(image widgets) overlap if QMainWindow is shrinked. Check the image below
The whole application is apparently not suited for different screens. Running this application on a laptop, layout is completely messed up.
What have i done:
Here is the MVCE code i have created
//ImageWidget.h
#ifndef IMAGEWIDGET_H
#define IMAGEWIDGET_H
#include <QLabel>
#include <QResizeEvent>
#include <QWidget>
class ImageWidget : public QLabel
{
Q_OBJECT
public:
explicit ImageWidget(QWidget* parent = nullptr);
virtual QSize sizeHint() const;
QPixmap scaledPixmap() const;
virtual int widthForHeight(int height) const;
public slots:
void setPixmap ( const QPixmap& p);
void resizeEvent(QResizeEvent* ev);
private:
QPixmap pix;
};
#endif // IMAGEWIDGET_H
ImageWidget.cpp
#include "imagewidget.h"
ImageWidget::ImageWidget(QWidget* parent) :
QLabel(parent)
{
setStyleSheet("QLabel{margin-left: 10px; border-radius: 25px; background: white; color: #4A0C46;}");
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setWidthForHeight(true);
setSizePolicy(sizePolicy);
setMinimumSize(sizeHint());
}
void ImageWidget::setPixmap (const QPixmap& p)
{
pix = p;
QLabel::setPixmap(scaledPixmap());
}
/* virtual */ int ImageWidget::widthForHeight(int height) const
{
return pix.isNull() ? height * pix.height() / pix.width() : height;
}
QSize ImageWidget::sizeHint() const
{
if(pix.width() != 0)
{
int h = this->height();
return QSize(widthForHeight(h), h);
}
else
{
return QSize(300, 300);
}
}
QPixmap ImageWidget::scaledPixmap() const
{
auto scaled = pix.scaled(this->size() * devicePixelRatioF(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
scaled.setDevicePixelRatio(devicePixelRatioF());
return scaled;
}
void ImageWidget::resizeEvent(QResizeEvent* )
{
if (!pix.isNull())
{
QLabel::setPixmap(scaledPixmap());
}
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QTableWidget>
#include "imagewidget.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
protected:
virtual void resizeEvent(QResizeEvent* event) override;
private:
Ui::MainWindow *ui;
ImageWidget* lbl1;
ImageWidget* lbl2;
ImageWidget* lbl3;
ImageWidget* lbl4;
QPushButton* btn1;
QPushButton* btn2;
QPushButton* btn3;
QPushButton* btn4;
QTableWidget* tableWidget;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QTabWidget>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QTabBar>
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QVBoxLayout* mainLayout = new QVBoxLayout;
QVBoxLayout* tabLay = new QVBoxLayout;
QHBoxLayout* buttonLay = new QHBoxLayout;
QGridLayout* gridLay = new QGridLayout;
QHBoxLayout* dockLay = new QHBoxLayout;
btn1 = new QPushButton(this);
btn1->setText("Button1");
btn2 = new QPushButton(this);
btn2->setText("Button2");
btn3 = new QPushButton(this);
btn3->setText("Button3");
btn4 = new QPushButton(this);
btn4->setText("Button4");
QTabWidget* tabView = new QTabWidget(this);
tabView->addTab(new QWidget(), "Table");
tabView->setMinimumSize(500, 300);
tabView->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
tableWidget = new QTableWidget(this);
tableWidget->setFixedHeight(200);
lbl1 = new ImageWidget(this);
lbl2 = new ImageWidget(this);
lbl3 = new ImageWidget(this);
lbl4 = new ImageWidget(this);
QPixmap lbl1Pix("1.png");
QPixmap lbl2Pix("2.png");
QPixmap lbl3Pix("3.png");
QPixmap lbl4Pix("4.png");
lbl1->setPixmap(lbl1Pix);
lbl1->show();
lbl2->setPixmap(lbl2Pix);
lbl2->show();
lbl3->setPixmap(lbl3Pix);
lbl3->show();
lbl4->setPixmap(lbl4Pix);
lbl4->show();
buttonLay->addWidget(btn1);
buttonLay->addWidget(btn2);
buttonLay->addWidget(btn3);
buttonLay->addWidget(btn4);
tabLay->addWidget(tabView);
gridLay->addWidget(lbl1, 0, 0);
gridLay->addWidget(lbl2, 0, 1);
gridLay->addWidget(lbl3, 1, 0);
gridLay->addWidget(lbl4, 1, 1);
dockLay->addLayout(gridLay);
dockLay->addLayout(tabLay);
mainLayout->addLayout(dockLay);
mainLayout->addLayout(buttonLay);
mainLayout->addWidget(tableWidget);
centralWidget()->setLayout(mainLayout);
setMinimumSize(200,200);
show();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeEvent(QResizeEvent * /*event*/)
{
// get label dimensions
int h = lbl1->height();
int w = lbl1->widthForHeight(h);
lbl1->setFixedWidth(w);
lbl2->setFixedWidth(w);
lbl3->setFixedWidth(w);
lbl4->setFixedWidth(w);
}
Main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
What do i want:
Set a minimum size to the whole application so that the imagewidgets do not overlap.
Make the whole app work on any PC or laptop screen with different resolutions.
The imagewidgets should take up available space while keeping the aspect ratio of the images and the QTabWidget on the right should have a fixed size.
Maybe there is an easy solution but i am bit confused with Qt Layout management system.
EDIT1: Added the image with overlapping widgets

Here is what I think is happening. When you set the pixmap like here:
QLabel::setPixmap(scaledPixmap());
The label will set the size of the images as the minimum size. And from that point on the label can not be resized any smaller.
The solution I have found around this is to set the following resize flags for the QLabel in the constructor:
QSizePolicy sizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
setSizePolicy(sizePolicy);
This way the QLabel will be resizable at all times. Or you might have to adapt the minimum width.
I am not sure if that is even it, but maybe it is a good start. Let me know what you make of this.

Related

How to set desired layout to the elements in different classes in c++ qt?

I am working on a project in which I am supposed to make two buttons(These buttons are named as Power calculation and Power calculation 2 ). When the user clicks on the buttons, a sliding area opens up under the buttons.
I have written this code successfully, but my problem is the layout of these buttons and the sliding area bellow each button(The buttons are defined in separate classes. The button named as "Power calculation" is defined in "Section.cpp" and the button named as "Power calculation 2" is defined in "Section2.cpp").
My goal is to set the buttons in the same row (the button named as "power calculation" must be on the left side of the button named as "Powercalculation2" and both of them are supposed to be in the same row). I use QGridLayout to set the layouts to my elements, but I can't get results. I have also tried to use move() and setGeometry() , but I could not get what I want to do.
I would appreciate if someone could help me in this matter.
The picture below is what I get after running my program:
But the result that I want to get is the picture below:
MY project ui file picture:
Here is my code:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
Section.h:
#ifndef SECTION_H
#define SECTION_H
#include <QFrame>
#include <QGridLayout>
#include <QParallelAnimationGroup>
#include <QScrollArea>
#include <QGridLayout>
#include <QParallelAnimationGroup>
#include <QScrollArea>
#include <QToolButton>
#include <QWidget>
#include "Section2.h"
class Section : public QWidget {
Q_OBJECT
private:
QGridLayout* mainLayout;
QToolButton* toggleButton;
QFrame* headerLine;
QParallelAnimationGroup* toggleAnimation;
QScrollArea* contentArea;
int animationDuration;
public slots:
void toggle(bool collapsed);
public:
explicit Section(const QString & title = "", const int animationDuration = 100, QWidget* parent =
0);
void setContentLayout(QLayout & contentLayout);
};
#endif // SECTION_H
Section2.h:
#ifndef SECTION2_H
#define SECTION2_H
#include <QFrame>
#include <QGridLayout>
#include <QParallelAnimationGroup>
#include <QScrollArea>
#include <QGridLayout>
#include <QParallelAnimationGroup>
#include <QScrollArea>
#include <QToolButton>
#include <QWidget>
class Section2 : public QWidget {
Q_OBJECT
private:
QGridLayout* mainLayout;
QToolButton* toggleButton;
QFrame* headerLine;
QParallelAnimationGroup* toggleAnimation;
QScrollArea* contentArea;
int animationDuration;
public slots:
void toggle(bool collapsed);
public:
explicit Section2(const QString & title = "", const int animationDuration = 100, QWidget* parent =
0);
void setContentLayout(QLayout & contentLayout);
};
#endif // SECTION_H
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Section.h"
#include "Section2.h"
#include <QLabel>
#include <QPushButton>
#include <QBoxLayout>
#include <QLineEdit>
#include <QGridLayout>
#include <QComboBox>
#include <QDebug>
#include <QRegularExpressionValidator>
#include <QValidator>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
Section *section = new Section("Section", 100, ui->centralWidget);
ui->centralWidget->layout()->addWidget(section);
Section2 *section2 = new Section2("Section2", 100, ui->centralWidget);
ui->centralWidget->layout()->addWidget(section2);
QVBoxLayout* anyLayout = new QVBoxLayout();
QLabel *lblV = new QLabel("insert voltage",section);
anyLayout->addWidget(lblV);
QLineEdit *lineV = new QLineEdit("",section);
anyLayout->addWidget(lineV);
QLabel *lblI = new QLabel("insert current",section);
anyLayout->addWidget(lblI);
QLineEdit *lineI = new QLineEdit("",section);
anyLayout->addWidget(lineI);
QPushButton *btn = new QPushButton("power: ",section);
anyLayout->addWidget(btn);
QLabel *lbl = new QLabel("",section);
lbl->setStyleSheet("background-color: yellow");
anyLayout->addWidget(lbl);
QVBoxLayout* anyLayout2 = new QVBoxLayout();
QLabel *lblV2 = new QLabel("insert voltage",section2);
anyLayout2->addWidget(lblV2);
QLineEdit *lineV2 = new QLineEdit("",section2);
anyLayout2->addWidget(lineV2);
QLabel *lblI2 = new QLabel("insert current",section2);
anyLayout2->addWidget(lblI2);
QLineEdit *lineI2 = new QLineEdit("",section2);
anyLayout2->addWidget(lineI2);
QPushButton *btn2 = new QPushButton("power: ",section2);
anyLayout2->addWidget(btn2);
QLabel *lbl2 = new QLabel("",section2);
lbl2->setStyleSheet("background-color: pink");
anyLayout2->addWidget(lbl2);
section->setContentLayout(*anyLayout);
section2->setContentLayout(*anyLayout2);
}
MainWindow::~MainWindow()
{
delete ui;
}
Section.cpp:
#include <QPropertyAnimation>
#include "Section.h"
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
Section::Section(const QString & title, const int animationDuration, QWidget* parent)
: QWidget(parent), animationDuration(animationDuration)
{
toggleButton = new QToolButton(this);
headerLine = new QFrame(this);
toggleAnimation = new QParallelAnimationGroup(this);
contentArea = new QScrollArea(this);
mainLayout = new QGridLayout(this);
toggleButton->setStyleSheet("QToolButton {border: none;}");
toggleButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toggleButton->setArrowType(Qt::ArrowType::RightArrow);
toggleButton->setText("Power calculation");
toggleButton->setCheckable(true);
toggleButton->setChecked(false);
headerLine->setFrameShape(QFrame::HLine);
headerLine->setFrameShadow(QFrame::Sunken);
headerLine->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
contentArea->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// start out collapsed
contentArea->setMaximumHeight(0);
toggleAnimation->addAnimation(new QPropertyAnimation(contentArea, "maximumHeight"));
mainLayout->setVerticalSpacing(0);
mainLayout->addWidget(toggleButton, 0, 0, 1, 1);
mainLayout->addWidget(headerLine, 0, 1, 1, 1);
mainLayout->addWidget(contentArea, 3, 0, 1, 3);
setLayout(mainLayout);
connect(toggleButton, &QToolButton::toggled, this, &Section::toggle);
}
void Section::toggle(bool collapsed) {
toggleButton->setArrowType(collapsed ? Qt::ArrowType::DownArrow : Qt::ArrowType::RightArrow);
toggleAnimation->setDirection(collapsed ? QAbstractAnimation::Forward :
QAbstractAnimation::Backward);
toggleAnimation->start();
}
void Section::setContentLayout(QLayout & contentLayout)
{
delete contentArea->layout();
contentArea->setLayout(&contentLayout);
const auto collapsedHeight = sizeHint().height() - contentArea->maximumHeight();
auto contentHeight = contentLayout.sizeHint().height();
for (int i = 0; i < toggleAnimation->animationCount() - 1; ++i)
{
QPropertyAnimation* SectionAnimation = static_cast<QPropertyAnimation *>(toggleAnimation->animationAt(i));
SectionAnimation->setDuration(animationDuration);
SectionAnimation->setStartValue(collapsedHeight);
SectionAnimation->setEndValue(collapsedHeight + contentHeight);
}
QPropertyAnimation* contentAnimation = static_cast<QPropertyAnimation *>(toggleAnimation->animationAt(toggleAnimation->animationCount() - 1));
contentAnimation->setDuration(animationDuration);
contentAnimation->setStartValue(0);
contentAnimation->setEndValue(contentHeight);
}
Section2.cpp:
#include <QPropertyAnimation>
#include "Section2.h"
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
Section2::Section2(const QString & title, const int animationDuration, QWidget* parent)
: QWidget(parent), animationDuration(animationDuration)
{
toggleButton = new QToolButton(this);
headerLine = new QFrame(this);
toggleAnimation = new QParallelAnimationGroup(this);
contentArea = new QScrollArea(this);
mainLayout = new QGridLayout(this);
toggleButton->setStyleSheet("QToolButton {border: none;}");
toggleButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toggleButton->setArrowType(Qt::ArrowType::RightArrow);
toggleButton->setText("Power calculation 2");
toggleButton->setCheckable(true);
toggleButton->setChecked(false);
headerLine->setFrameShape(QFrame::HLine);
headerLine->setFrameShadow(QFrame::Sunken);
headerLine->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
contentArea->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// start out collapsed
contentArea->setMaximumHeight(0);
toggleAnimation->addAnimation(new QPropertyAnimation(contentArea, "maximumHeight"));
mainLayout->setVerticalSpacing(0);
mainLayout->addWidget(toggleButton, 0, 0, 1, 1);
mainLayout->addWidget(headerLine, 0, 1, 1, 1);
mainLayout->addWidget(contentArea, 3, 0, 1, 3);
setLayout(mainLayout);
connect(toggleButton, &QToolButton::toggled, this, &Section2::toggle);
}
void Section2::toggle(bool collapsed) {
toggleButton->setArrowType(collapsed ? Qt::ArrowType::DownArrow : Qt::ArrowType::RightArrow);
toggleAnimation->setDirection(collapsed ? QAbstractAnimation::Forward :
QAbstractAnimation::Backward);
toggleAnimation->start();
}
void Section2::setContentLayout(QLayout & contentLayout)
{
delete contentArea->layout();
contentArea->setLayout(&contentLayout);
const auto collapsedHeight = sizeHint().height() - contentArea->maximumHeight();
auto contentHeight = contentLayout.sizeHint().height();
for (int i = 0; i < toggleAnimation->animationCount() - 1; ++i)
{
QPropertyAnimation* SectionAnimation = static_cast<QPropertyAnimation *>(toggleAnimation-
>animationAt(i));
SectionAnimation->setDuration(animationDuration);
SectionAnimation->setStartValue(collapsedHeight);
SectionAnimation->setEndValue(collapsedHeight + contentHeight);
}
QPropertyAnimation* contentAnimation = static_cast<QPropertyAnimation *>(toggleAnimation-
>animationAt(toggleAnimation->animationCount() - 1));
contentAnimation->setDuration(animationDuration);
contentAnimation->setStartValue(0);
contentAnimation->setEndValue(contentHeight);
}
You have 2 widgets (Section and Section2) that contain other widgets (buttons/labels) that you want to be placed horizontally in your main window (inside centralWidget).
For that you need to set the appropriate layout to the centralWidget and add Section* items to that layout.
Right now, you just use the default layout of the centralWidget:
Section *section = new Section("Section", 100, ui->centralWidget);
ui->centralWidget->layout()->addWidget(section);
Section2 *section2 = new Section2("Section2", 100, ui->centralWidget);
ui->centralWidget->layout()->addWidget(section2);
I use QGridLayout to set the layouts to my elements, but I can't get results.
This is because in your code you use QGridLayout to lay out the widgets inside each instance of Section and Section2.
mainLayout->addWidget(toggleButton, 0, 0, 1, 1);
mainLayout->addWidget(headerLine, 0, 1, 1, 1);
mainLayout->addWidget(contentArea, 3, 0, 1, 3);
setLayout(mainLayout);
This controls how toggleButton, headerLine and contentArea are laid out inside Section* widgets, but has no effect on how Section widgets itself are positioned with respect to each other in some "higher level" widget (centralWidget in this case).
When you create your Section* widgets you can think of them as any other standard widget (button/label/etc.) and handle them accordingly.

Dynamically resizing two QLabel implementations

I'm trying to create a simple frame in Qt with a tick and some text. I made two new label implementations because I wanted the labels to dynamically fill all the available space but when I resize the window the sizes are off, as shown by the qDebug output, which represents the size of the image label:
Resized: 244 , 244 <-- Window first created
Resized: 305 , 305 <-- Window maximized
Resized: 135 , 135 <-- Window restored to original size
As you can see, when the window is restored to its original size the image is not. The last size should be 244, 244.
The code which describes the behaviour of the two widgets is the following:
"widgets.h":
/*
* This file includes many custom widgets.
*/
#ifndef APOCRYPHA_WIDGETS
#define APOCRYPHA_WIDGETS
#include <QWidget>
#include <QLabel>
#include <QTimer>
#include <QPixmap>
#include <QResizeEvent>
#include <QPaintEvent>
class AutoTextLabel : public QLabel {
Q_OBJECT
public:
explicit AutoTextLabel(QWidget* parent);
AutoTextLabel(QWidget* parent, QString text);
protected:
void resizeEvent(QResizeEvent* event) override;
private:
QTimer* resizeTimer;
private slots:
void onResizeEnd();
};
class AutoImageLabel : public QLabel {
Q_OBJECT
public:
explicit AutoImageLabel(QWidget* parent);
AutoImageLabel(QWidget* parent, const QPixmap& pixmap);
void setFillOrientation(int orientation);
QSize sizeHint() const override;
public slots:
void setPixmap(const QPixmap &newPix);
void resizeEvent(QResizeEvent* event) override;
protected:
// void paintEvent(QPaintEvent* event) override;
private:
int fillOrientation;
int widthForHeight(int h) const;
int heightForWidth(int w) const override;
QPixmap scaledPixmap() const;
QPixmap labelPixmap;
};
#endif //APOCRYPHA_WIDGETS
"widgets.cpp":
/*
* This file includes many custom widgets.
*/
#include "widgets.h"
#include <QPainter>
#include <QDebug>
AutoTextLabel::AutoTextLabel(QWidget *parent, QString text) : QLabel(text, parent){
// Enable antialiasing
QFont aaFont(font());
aaFont.setStyleStrategy(QFont::PreferAntialias);
setFont(aaFont);
// This timer is used to fire a slot when a window is resized
resizeTimer = new QTimer();
resizeTimer->setSingleShot(true);
connect(resizeTimer, SIGNAL(timeout()), SLOT(onResizeEnd()));
}
AutoTextLabel::AutoTextLabel(QWidget *parent) : AutoTextLabel(parent, "") {}
void AutoTextLabel::resizeEvent(QResizeEvent *event) {
QWidget::resizeEvent(event);
// Only fire when 25ms have passed since the last resize.
resizeTimer->start(25);
}
void AutoTextLabel::onResizeEnd() {
QFont updatedFont(font());
// Resize Text
if (!text().isEmpty()){
int fontSize = 1;
updatedFont.setPixelSize(fontSize);
QRect boundingRectangle;
// Update bounding rectangle
if (wordWrap())
boundingRectangle = QFontMetrics(updatedFont).boundingRect(contentsRect(), Qt::TextWordWrap, text());
else
boundingRectangle = QFontMetrics(updatedFont).boundingRect(text());
while (boundingRectangle.height() <= contentsRect().height()) {
fontSize++;
updatedFont.setPixelSize(fontSize);
// Update bounding rectangle
if (wordWrap())
boundingRectangle = QFontMetrics(updatedFont).boundingRect(contentsRect(), Qt::TextWordWrap, text());
else
boundingRectangle = QFontMetrics(updatedFont).boundingRect(text());
}
updatedFont.setPixelSize(fontSize - 1);
setFont(updatedFont);
}
}
/* Auto Image Label */
AutoImageLabel::AutoImageLabel(QWidget *parent, const QPixmap &pixmap) : QLabel(parent) {
setMinimumSize(1, 1);
setScaledContents(false);
setPixmap(pixmap);
}
AutoImageLabel::AutoImageLabel(QWidget *parent) : QLabel(parent) {
setScaledContents(false);
}
void AutoImageLabel::resizeEvent(QResizeEvent *event) {
QWidget::resizeEvent(event);
if(!labelPixmap.isNull())
QLabel::setPixmap(scaledPixmap());
qDebug() << "Resized: " << scaledPixmap().width() << ", " << scaledPixmap().height();
}
int AutoImageLabel::widthForHeight(int h) const {
return labelPixmap.isNull() ? width() : (labelPixmap.width() * h) / labelPixmap.height();
}
int AutoImageLabel::heightForWidth(int w) const {
return labelPixmap.isNull() ? height() : (labelPixmap.height() * w) / labelPixmap.width();
}
void AutoImageLabel::setFillOrientation(int orientation) {
this->fillOrientation = orientation;
}
QSize AutoImageLabel::sizeHint() const {
if (fillOrientation == Qt::Horizontal)
return QSize(width(), heightForWidth(width()));
else
return QSize(widthForHeight(height()), height());
}
QPixmap AutoImageLabel::scaledPixmap() const {
return labelPixmap.scaled(sizeHint(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
void AutoImageLabel::setPixmap(const QPixmap &newPix) {
labelPixmap = newPix;
QLabel::setPixmap(scaledPixmap());
}
"other_frames.h":
//
// Created by Riccardo on 18/09/2017.
//
#ifndef APOCRYPHA_OTHER_FRAMES_H
#define APOCRYPHA_OTHER_FRAMES_H
#include <QFrame>
#include <QLabel>
#include <QGridLayout>
#include <QWidget>
#include <QResizeEvent>
#include <QPixmap>
#include <QTimer>
#include "widgets.h"
class ConfirmationFrame : public QFrame {
Q_OBJECT
public:
explicit ConfirmationFrame(QWidget* parent);
ConfirmationFrame(QWidget* parent, const QString& text);
private:
QGridLayout* layout;
AutoImageLabel* imageLabel;
AutoTextLabel* textLabel;
};
#endif //APOCRYPHA_OTHER_FRAMES_H
"other_frames.cpp":
//
// Created by Riccardo on 18/09/2017.
//
#include "other_frames.h"
#include <QDebug>
ConfirmationFrame::ConfirmationFrame(QWidget* parent, const QString &text) : QFrame(parent) {
textLabel = new AutoTextLabel(this, text);
QPixmap pix(":/images/check-tick.png");
imageLabel = new AutoImageLabel(this, pix);
textLabel->setAlignment(Qt::AlignCenter);
imageLabel->setAlignment(Qt::AlignCenter);
textLabel->setWordWrap(true);
// Green Background
setStyleSheet("background-color: rgba(106, 242, 94, 1);");
layout = new QGridLayout();
layout->setSpacing(0);
layout->setContentsMargins(32, 32, 32, 32);
layout->setRowStretch(0, 1);
layout->setRowStretch(1, 1);
layout->addWidget(imageLabel, 0, 1);
layout->addWidget(textLabel, 1, 1);
setLayout(layout);
}
ConfirmationFrame::ConfirmationFrame(QWidget *parent) : ConfirmationFrame(parent, "") {
}
"window_main.h":
#ifndef WINDOW_MAIN_H
#define WINDOW_MAIN_H
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QGridLayout>
#include <QFrame>
#include <QScreen>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
QFrame *mainFrame;
void center(QScreen* screen);
void autoSetSize(QScreen* screen);
private:
void createMenu();
// Components
QGridLayout *mainLayout;
QMenuBar *menuBar;
QMenu *fileMenu;
};
#endif // WINDOW_MAIN
"window_main.cpp":
#include "window_main.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
mainFrame = new QFrame();
mainLayout = new QGridLayout();
mainLayout->setSpacing(0);
mainLayout->setContentsMargins(0, 0, 0, 0);
createMenu();
mainFrame->setStyleSheet("background-color: red;");
mainFrame->setLayout(mainLayout);
setCentralWidget(mainFrame);
}
void MainWindow::createMenu(){
menuBar = new QMenuBar;
fileMenu = new QMenu(tr("&File"), this);
menuBar->addMenu(fileMenu);
setMenuBar(menuBar);
}
void MainWindow::center(QScreen *screen) {
QSize size = screen->availableSize();
int x = size.width() / 2 - width() / 2;
int y = size.height() / 2 - height() / 2;
move(x, y);
}
void MainWindow::autoSetSize(QScreen *screen) {
QSize screenSize = screen->availableSize();
// TODO Math.round
setMinimumSize(QSize((int)(screenSize.width() / 1.25), (int)(screenSize.height() / 1.25)));
}
"main.cpp":
#include <QApplication>
#include <iostream>
#include <QFile>
#include "quiz/choice.h"
#include "quiz/question.h"
#include "quiz/quizmaker.h"
#include <QSettings>
#include <QStandardPaths>
#include <QDebug>
#include <src/user_interface/other_frames.h>
#include "user_interface/window_main.h"
#include <QScreen>
#include <QFontDatabase>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
// Set Application Parameters
QCoreApplication::setOrganizationName("Riccardo Fagiolo");
QCoreApplication::setOrganizationDomain("kopharex.me");
QCoreApplication::setApplicationName("Apocrypha");
// Set application font
const int id = QFontDatabase::addApplicationFont(":/fonts/montserrat/Montserrat-Regular.otf");
QString family = QFontDatabase::applicationFontFamilies(id).at(0);
QFont font(family);
font.setStyleStrategy(QFont::PreferAntialias);
a.setFont(font);
// App Settings
QSettings settings;
settings.setValue("data_dir", QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
// Create UI
auto* window = new MainWindow();
ConfirmationFrame* cframe = new ConfirmationFrame(window, "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?");
window->mainFrame->layout()->addWidget(cframe);
window->autoSetSize(a.primaryScreen());
//cframe->updateTextLabel();
window->show();
window->center(a.primaryScreen());
// [...] - Nothing related to user interface.
return a.exec();
}
Here is a screenshot of the current MainWindow and ConfirmationFrame to give you an idea of what i'm trying to accomplish:
Window Screenshot
All comments regarding the code are welcome.
Thanks for any help,
Riccardo
Hello I tried to fix the resizing issue with an hack.
Before starting the timer to resize the text, just reduce its font to a 1 pixel font:
void AutoTextLabel::resizeEvent(QResizeEvent *event) {
QWidget::resizeEvent(event);
// set a very small font, then start the timer
QFont updatedFont(font());
updatedFont.setPixelSize(1);
setFont(updatedFont);
// Only fire when 25ms have passed since the last resize.
resizeTimer->start(25);
}
Can the effect be acceptable in your opinion?

Using QPainter to draw a line between QWidgets

I'm working on an application where I need to be able to draw a line between two QWidget objects. I have tried quite a few things, but my current attempt (which I think is in the right direction I just think I'm missing something) is to have the containing widget (which I called DrawWidget and which holds the QGridLayout that the QWidget objects are added to) override the paintEvent method and call the QPainter::drawLine() function.
The issues I'm having are that:
No matter how I try to get the position of the widgets, the endpoints of the line are always in the wrong place
Whenever I try to draw a second line, the first line that I drew gets erased.
Here is the paintEvent function of the containing widget:
void paintEvent(QPaintEvent *)
{
if (!drewSinceUpdate){
drewSinceUpdate = true;
QPainter painter(this);
painter.setPen(QPen(Qt::black));
painter.drawLine(start->geometry().center(), end->geometry().center());
}
}
I have tried many different ways to get the correct position of the widgets in the last line of paintEvent, which I will post some of the ways (I can't remember all of them):
painter.drawLine(start->pos(), end->pos());
painter.drawLine(start->mapToGlobal(start->geometry().center()), end->mapToGlobal(end->geometry().center()));
painter.drawLine(this->mapToGlobal(start->geometry().center()), this->mapToGlobal(end->geometry().center()));
painter.drawLine(start->mapTo(this, start->pos()), end->mapTo(this, end->pos()));
painter.drawLine(this->mapFrom(start, start->pos()), this->mapFrom(end, end->pos()));
And just to make my question clear, here is an example of what I am looking for, taken from QT Diagram Scene Example:
But this is what I end up getting:
Thank you for any help you can provide.
NOTE:
-start and end are both QWidget objects which I passed in using another method
-The hierarchy relevant to DrawWidget is:
QMainWindow
->QScrollArea
->DrawWidget
->QGridLayout
->Items <-- These are the things I want to connect
EDIT: To make a Complete and Verifiable example, here is the entirety of the relevant code.
MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QScrollBar>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Setting up the relevant hierarchy
ui->setupUi(this);
scrollArea = new QScrollArea();
setCentralWidget(scrollArea);
drawWidget = new DrawWidget();
gridLayout = new QGridLayout();
gridLayout->setSpacing(300);
drawWidget->setLayout(gridLayout);
scrollArea->setWidget(drawWidget);
scrollArea->setWidgetResizable(true);
AddItemSlot();
QApplication::connect(scrollArea->horizontalScrollBar(), SIGNAL(rangeChanged(int,int)), this, SLOT(scrollHorizontal()));
}
// This is just creating a single one of the example widgets which I want to connect
QWidget* MainWindow::CreateNewItem(){
QWidget* itemWidget = new QWidget();
itemWidget->setStyleSheet("background-color: lightgray");
QHBoxLayout* singleItemLayout = new QHBoxLayout();
itemWidget->setLayout(singleItemLayout);
QTextEdit* textEdit = new QTextEdit(std::to_string(counter++).c_str());
textEdit->setStyleSheet("background-color:white;");
singleItemLayout->addWidget(textEdit);
QVBoxLayout* rightSidePanel = new QVBoxLayout();
rightSidePanel->setAlignment(Qt::AlignTop);
QPushButton* button1 = new QPushButton("Top Button");
QApplication::connect(button1, SIGNAL(clicked(bool)), this, SLOT(AddItemSlot()));
rightSidePanel->addWidget(button1);
QWidget* rightPanelWidget = new QWidget();
rightSidePanel->setMargin(0);
rightPanelWidget->setLayout(rightSidePanel);
singleItemLayout->addWidget(rightPanelWidget);
itemWidget->setLayout(singleItemLayout);
itemWidget->setMinimumWidth(400);
itemWidget->setFixedSize(400,200);
return itemWidget;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::scrollHorizontal()
{
scrollArea->ensureWidgetVisible(noteItems.back());
}
void MainWindow::AddItemSlot()
{
QWidget* w = CreateNewItem();
gridLayout->addWidget(w,currRow, currCol++);
if (!noteItems.empty()){
drawWidget->updateEndpoints(noteItems.back(), w);
}
noteItems.push_back(w);
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QGridLayout>
#include <QWidget>
#include <QMainWindow>
#include <QScrollArea>
#include <drawwidget.h>
#include "drawscrollarea.h"
#include <vector>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void scrollHorizontal();
void AddItemSlot();
private:
Ui::MainWindow *ui;
QWidget* CreateNewItem();
int counter = 0, currCol = 0, currRow = 0;
std::vector<QWidget*> noteItems;
QScrollArea* scrollArea;
DrawWidget* drawWidget;
QGridLayout* gridLayout;
};
#endif // MAINWINDOW_H
DrawWidget.cpp:
#include "drawwidget.h"
#include <QDebug>
#include <QRect>
DrawWidget::DrawWidget(QWidget *parent) : QWidget(parent)
{
}
void DrawWidget::paintEvent(QPaintEvent *)
{
if (!drewSinceUpdate){
drewSinceUpdate = true;
QPainter painter(this);
painter.setPen(QPen(Qt::black));
for (ConnectedPair pair : items){
const QWidget* from = pair.from;
const QWidget* to =pair.to;
QPoint start = from->mapToGlobal(from->rect().topRight() + QPoint(0, from->height()/2));
QPoint end = to->mapToGlobal(to->rect().topLeft() + QPoint(0, to->height()/2));
painter.drawLine(mapFromGlobal(start), mapFromGlobal(end));
}
}
}
void DrawWidget::updateEndpoints(QWidget* startIn, QWidget* endIn){
drewSinceUpdate = false;
items.push_back(ConnectedPair{startIn, endIn});
}
DrawWidget.h
#ifndef DRAWWIDGET_H
#define DRAWWIDGET_H
#include <QWidget>
#include <QPainter>
#include <QtCore>
#include <vector>
class DrawWidget : public QWidget
{
Q_OBJECT
public:
explicit DrawWidget(QWidget *parent = nullptr);
void updateEndpoints(QWidget* startIn, QWidget* endIn);
virtual void paintEvent(QPaintEvent *);
signals:
private:
struct ConnectedPair {
const QWidget* from;
const QWidget* to;
};
std::vector<ConnectedPair> items;
bool drewSinceUpdate = true;
};
#endif // DRAWWIDGET_H
For this case we use the function mapToGlobal() and mapfromGlobal(), since pos() returns a position with respect to the parent and this can cause problems if the widget has different parents.
drawwidget.h
#ifndef DRAWWIDGET_H
#define DRAWWIDGET_H
#include <QWidget>
class DrawWidget : public QWidget
{
Q_OBJECT
public:
explicit DrawWidget(QWidget *parent = nullptr);
void addWidgets(const QWidget *from, const QWidget *to);
protected:
void paintEvent(QPaintEvent *);
private:
struct WidgetsConnected {
const QWidget* from;
const QWidget* to;
};
QList<WidgetsConnected> list;
};
#endif // DRAWWIDGET_H
drawwidget.cpp
#include "drawwidget.h"
#include <QPainter>
DrawWidget::DrawWidget(QWidget *parent) : QWidget(parent)
{
}
void DrawWidget::addWidgets(const QWidget * from, const QWidget * to)
{
list.append(WidgetsConnected{from , to});
update();
}
void DrawWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
for(const WidgetsConnected el: list){
const QWidget* from = el.from;
const QWidget* to = el.to;
QPoint start = from->mapToGlobal(from->rect().topRight() + QPoint(0, from->height()/2));
QPoint end = to->mapToGlobal(to->rect().topLeft() + QPoint(0, to->height()/2));
painter.drawLine(mapFromGlobal(start), mapFromGlobal(end));
}
}
The complete example can be found here.

Qt Catching signal of checkbox to do an action

In my Qt program, I want to catch the signal of one of my checkbox to know if it's checked or not. I did it :
#include <iostream>
#include <QVBoxLayout>
#include <QtGui>
#include "Window.h"
Window::Window() : QWidget()
{
setFixedSize(400, 800);
m_bouton = new QPushButton("Module 1");
m_bouton->setCursor(Qt::PointingHandCursor);
m_bouton2 = new QPushButton("Module 2");
m_bouton2->setCursor(Qt::PointingHandCursor);
m_bouton3 = new QPushButton("Module 3");
m_bouton3->setCursor(Qt::PointingHandCursor);
m_bouton4 = new QPushButton("Module 4");
m_bouton4->setCursor(Qt::PointingHandCursor);
m_check4 = new QCheckBox(this);
m_check4->move(300, 50);
m_check4->setChecked(true);
m_check3 = new QCheckBox(this);
m_check3->move(200, 50);
m_check3->setChecked(true);
m_check2 = new QCheckBox(this);
m_check2->move(100, 50);
m_check2->setChecked(true);
m_check1 = new QCheckBox(this);
m_check1->move(0, 50);
m_check1->setChecked(true);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_bouton);
layout->addWidget(m_bouton2);
layout->addWidget(m_bouton3);
layout->addWidget(m_bouton4);
this->setLayout(layout);
this->setStyleSheet("border: 1px solid black; border-radius: 10px;");
this->setWindowOpacity(0.5);
QWidget::setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
QWidget::setWindowTitle("Monitor Core");
QObject::connect(m_bouton4, SIGNAL(clicked()), this, SLOT(SizeCHange()));
QObject::connect(m_check4, SIGNAL(clicked()), this, SLOT(SizeCHange()));
}
void Window::SizeCHange()
{
setFixedSize(400, 800 - 200);
m_bouton4->setVisible(false);
}
and this is my .h :
#ifndef _WINDOW_H_
#define _WINDOW_H_
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QCheckBox>
class Window : public QWidget
{
Q_OBJECT
public:
Window();
public slots:
void SizeCHange();
private:
QPushButton *m_bouton;
QPushButton *m_bouton2;
QPushButton *m_bouton3;
QPushButton *m_bouton4;
QCheckBox *m_check1;
QCheckBox *m_check2;
QCheckBox *m_check3;
QCheckBox *m_check4;
};
#endif
This is working but just one time. I want to know if it's check or not, then I will be able to resize my window and make something invisible as I want.
You simply need to use a bool parameter, which indicates the state of the checkbox:
public slots:
void SizeCHange(bool checked); //using bool parameter
//...
QObject::connect(m_check4, SIGNAL(clicked(bool)), this, SLOT(SizeCHange(bool)));
//...
void Window::SizeCHange(bool checked)
{
if(checked)
{
setFixedSize(400, 800 - 200);
}
else
{
// removing fixed size
setMinimumSize(QSize(0, 0));
setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
}
m_bouton4->setVisible(checked);
}
The docs for a signal clicked()

Qt - QStackedWidget and QTabsExample help

Basically, I have multiple widgets I'm trying to switch between... and the default is a QTabWidget. Aside from some modification, the two examples (QStackedWidget and QTabsExapmle) are just mingled together. I can't get the "connect" portion to work (get an error: no matching function for call to QTabsExample::connect), and nothing displays on screen unless stackedWidget->addWidget(tabWidget) is the first in the list (and even then, I only see the view in the upper left hand corner).
QTabsExample.h
#ifndef QTABSEXAMPLE_H
#define QTABSEXAMPLE_H
#include <QtGui/QMainWindow>
#include <QtGui/QScrollArea>
#include <QtGui/QFrame>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QGroupBox>
#include <QtGui/QFormLayout>
#include <QtGui/QMessageBox>
#include <QtCore/QPointer>
#include <QtCore/QFile>
#include <QtCore/QIODevice>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QString>
#include <QtXml/QXmlStreamReader>
#include <QtDebug>
#include <QBool>
#include <QSignalMapper>
#include <QStackedLayout>
class QTabsExample: public QMainWindow {
Q_OBJECT
public:
QTabsExample(QWidget *parent = 0);
~QTabsExample();
private:
void buildTabMenuBar(int index);
public slots:
void activeTabChanged(int index);
void setCurrentIndex(int);
signals:
void activated(int);
private:
QTabWidget* tabWidget;
QWidget* customWidget1;
QWidget* customWidget2;
QWidget* customWidget3;
};
// ---------------------------------------------------------------------------
// QMyWidget - Tab1
//
class QMyWidget: public QWidget {
Q_OBJECT
public:
QMyWidget(QWidget *parent = 0);
~QMyWidget();
public slots:
void runOnTabSelect();
private:
QPointer<QVBoxLayout> _layout;
};
// ---------------------------------------------------------------------------
// QMyWidget2 - Tab2
//
class QMyWidget2: public QWidget {
Q_OBJECT
public:
QMyWidget2(QWidget *parent = 0);
~QMyWidget2();
public slots:
void runOnTabSelect();
};
// ---------------------------------------------------------------------------
// QMyWidget3 - Tab3
//
class QMyWidget3: public QWidget {
Q_OBJECT
public:
QMyWidget3(QWidget *parent = 0);
~QMyWidget3();
public slots:
void runOnTabSelect();
private:
QPointer<QVBoxLayout> _layout;
};
#endif // QTABSEXAMPLE_H
QTabsExample.cpp
#include <QtGui>
#include <QApplication>
#include "QTabsExample.h"
QTabsExample::QTabsExample(QWidget *parent) : QMainWindow(parent) {
setContextMenuPolicy(Qt::NoContextMenu);
this->setWindowTitle("Main Window, I think");
QStackedLayout *stackedLayout = new QStackedLayout;
//create tab widget
QTabWidget *tabWidget = new QTabWidget();
tabWidget->setContextMenuPolicy(Qt::NoContextMenu);
QObject::connect(tabWidget, SIGNAL(currentChanged(int)),this, SLOT(activeTabChanged(int)));
QMyWidget* widget1 = new QMyWidget();
tabWidget->addTab(widget1, "Tab1");
QMyWidget2* widget2 = new QMyWidget2();
tabWidget->addTab(widget2, "Tab2");
QMyWidget3* widget3 = new QMyWidget3();
tabWidget->addTab(widget3, "Tab3");
//set programatically
tabWidget->setStyleSheet("QTabBar::tab { height: 70px; width: 80px; font-size: 15px;}");
//create other widgets
QWidget* customWidget1 = new QWidget;
QWidget* customWidget2 = new QWidget;
QWidget* customWidget3 = new QWidget;
//add layouts to widgets
customWidget1->setContextMenuPolicy(Qt::NoContextMenu);
customWidget2->setContextMenuPolicy(Qt::NoContextMenu);
customWidget3->setContextMenuPolicy(Qt::NoContextMenu);
customWidget1->setWindowTitle("Widget 1");
customWidget2->setWindowTitle("Widget 2");
customWidget3->setWindowTitle("Widget 3");
//insert content to make sure it's viewable
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(QImage("c://default.png")));
customWidget1->setPalette(palette);
palette.setBrush(this->backgroundRole(), QBrush(QImage("c://default2.png")));
customWidget2->setPalette(palette);
palette.setBrush(this->backgroundRole(), QBrush(QImage("c://default3.png")));
customWidget3->setPalette(palette);
//add widgets to stack
stackedLayout->addWidget(tabWidget);
stackedLayout->addWidget(customWidget1);
stackedLayout->addWidget(customWidget2);
stackedLayout->addWidget(customWidget3);
QComboBox *pageComboBox = new QComboBox;
pageComboBox->addItem(tr("Tab Page"));
pageComboBox->addItem(tr("page 2"));
pageComboBox->addItem(tr("page 3"));
pageComboBox->addItem(tr("page 4"));
connect(pageComboBox, SIGNAL(activated(int))), stackedLayout, SLOT(setCurrentIndex(int));
QVBoxLayout *_layout = new QVBoxLayout;
_layout->addWidget(pageComboBox);
_layout->addLayout(stackedLayout);
setLayout(_layout);
//setCentralWidget(tabWidget);
#ifdef Q_OS_SYMBIAN
QWidgetList widgets = QApplication::allWidgets();
QWidget* w = 0;
foreach(w,widgets) {
w->setContextMenuPolicy(Qt::NoContextMenu);
}
#endif
}
QTabsExample::~QTabsExample(){
}
void QTabsExample::activeTabChanged(int index) {
buildTabMenuBar(index);
}
void QTabsExample::buildTabMenuBar(int index) {
QMenuBar* menubar = menuBar();
menubar->clear();
switch (index) {
case 0:
{
menubar->addAction("", tabWidget->widget(index), SLOT(runOnTabSelect()));
break;
}
case 1:
{
menubar->addAction("", tabWidget->widget(index), SLOT(runOnTabSelect()));
break;
}
case 2:
{
menubar->addAction("", tabWidget->widget(index), SLOT(runOnTabSelect()));
break;
}
default:
{
break;
}
};
}
//tab1
QMyWidget::QMyWidget(QWidget *parent) : QWidget(parent) {
setContextMenuPolicy(Qt::NoContextMenu);
QVBoxLayout* _layout = new QVBoxLayout(this);
//buttons get created
this->setLayout(_layout);
}
QMyWidget::~QMyWidget() {
}
void QMyWidget::runOnTabSelect() {
}
//tab2
QMyWidget2::QMyWidget2(QWidget *parent) : QWidget(parent) {
setContextMenuPolicy(Qt::NoContextMenu);
QVBoxLayout* _layout = new QVBoxLayout(this);
//buttons get created
this->setLayout(_layout);
}
QMyWidget2::~QMyWidget2() {
}
void QMyWidget2::runOnTabSelect() {
}
//tab3
QMyWidget3::QMyWidget3(QWidget *parent) : QWidget(parent) {
setContextMenuPolicy(Qt::NoContextMenu);
QVBoxLayout* _layout = new QVBoxLayout(this);
//buttons get created
this->setLayout(_layout);
}
QMyWidget3::~QMyWidget3() {
}
void QMyWidget3::runOnTabSelect() {
}
main.cpp
#include "QTabsExample.h""
#include <QtGui>
#include <QApplication>
#include <QtGui/QApplication>
#include <QPixmap>
#include <QWidget>
#include <QMainWindow>
#include <QSplashScreen>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTabsExample w;
w.showMaximized();
return a.exec();
}
Well for starters you need to uncomment //QTabsExample w; in main.cpp, but I guess, that is just a relict from experimenting...
Also, what do you mean by "nothing displays on screen."?
Do you mean, that an empty window pops up? Or does no window at all open? Or does the screen turn black?
Have you eliminated the possibility that the "app.css" file might be corrupt?
Have you tried deleting the Makefiles and moc_* files?
EDIT:
I tried to simplify the constructor of QTabsExample
#include <QtGui>
#include <QApplication>
#include "QTabsExample.h"
QTabsExample::QTabsExample(QWidget *parent) : QMainWindow(parent) {
setContextMenuPolicy(Qt::NoContextMenu);
this->setWindowTitle("Main Window, I think");
//create tab widget
QTabWidget *tabWidget = new QTabWidget();
tabWidget->setContextMenuPolicy(Qt::NoContextMenu);
//QObject::connect(tabWidget, SIGNAL(currentChanged(int)),this, SLOT(activeTabChanged(int))); // I have no experience with mobile developement
// can you manipulate the menubar on a mobile device?
QMyWidget* widget1 = new QLabel(tr("Widget1")); // simplification
tabWidget->addTab(widget1, "Tab1");
QMyWidget2* widget2 = new QLabel(tr("Widget2"));
tabWidget->addTab(widget2, "Tab2");
QMyWidget3* widget3 = new QLabel(tr("Widget3"));
tabWidget->addTab(widget3, "Tab3");
//set programatically
tabWidget->setStyleSheet("QTabBar::tab { height: 70px; width: 80px; font-size: 15px;}");
//create other widgets
QWidget* customWidget1 = new QLabel(tr("Hello1")); // simplification
QWidget* customWidget2 = new QLabel(tr("Hello2"));
QWidget* customWidget3 = new QLabel(tr("Hello3"));
// create stacked layout (closer to where it is actually used)
QStackedLayout *stackedLayout = new QStackedLayout;
//add widgets to stack
stackedLayout->addWidget(tabWidget);
stackedLayout->addWidget(customWidget1);
stackedLayout->addWidget(customWidget2);
stackedLayout->addWidget(customWidget3);
QComboBox *pageComboBox = new QComboBox;
pageComboBox->addItem(tr("Tab Page"));
pageComboBox->addItem(tr("page 2"));
pageComboBox->addItem(tr("page 3"));
pageComboBox->addItem(tr("page 4"));
connect(pageComboBox, SIGNAL(activated(int))), stackedLayout, SLOT(setCurrentIndex(int));
QVBoxLayout *_layout = new QVBoxLayout;
_layout->addWidget(pageComboBox);
_layout->addLayout(stackedLayout);
setLayout(_layout);
//setCentralWidget(tabWidget);
#ifdef Q_OS_SYMBIAN
QWidgetList widgets = QApplication::allWidgets();
QWidget* w = 0;
foreach(w,widgets) {
w->setContextMenuPolicy(Qt::NoContextMenu);
}
#endif
}
Expected behaviour:
a combo box on the top with choices: "Tab Page", "page 2", ...
below a QTabWidget witht the tabs: "Tab1", "Tab2", "Tab3"
Tab1 should be displayed with a QLabel, which says "Widget1"
when you select another tab, the label should say "WidgetX" // depending on your choice
when you select another widget from the combo box you should see "HelloX" // depending on your choice