0

I would like to add the status bar to my program, but I can't find any examples of it online.

I saw few people using some forms which I don't use. I would like my status bar to be able to show text length and his coordinates. And also I would like to refresh it after every change (changing the text and it's position).

My code currently can change the display text, change it's position using mouse or keyboard and save that data into a file or open that file and load data.

My code:

#include <QApplication>
#include <QLabel>
#include <QMainWindow>
#include <QMouseEvent>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <QPainter>
#include <QFileDialog>
#include <QTextStream>
#include <QStatusBar>
#include <QProgressBar>
#include <QTextEdit>

class MyDialog : public QDialog {
public:
    MyDialog();
    QVBoxLayout* mainLayout;
    QWidget* editWidget;
    QFormLayout* editLayout;
    QLineEdit* lineEdit;
    QDialogButtonBox* buttonBox;

};

MyDialog::MyDialog() {
    lineEdit = new QLineEdit;
    editLayout = new QFormLayout;
    editLayout->addRow(new QLabel(tr("Novi tekst:")), lineEdit);
    editWidget = new QWidget;
    editWidget->setLayout(editLayout);
    buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok |QDialogButtonBox::Cancel);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
    mainLayout = new QVBoxLayout;
    mainLayout->addWidget(editWidget);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);
    setWindowTitle("Promjena teksta");

}


class MyMainWindow : public QMainWindow {
public:
    MyMainWindow();
    QLabel* MyLabel;
    QMenu* EditMenu;
    QAction* EditNoviTekst;
    QString* String;
    QString*poz;
    int a,b;


    void mousePressEvent(QMouseEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void paintEvent(QPaintEvent *event) override;

    void EditNoviTekstMenu();


    void FileSaveAsMenu();
    void FileOpenMenu();
    QMenu* FileMenu;
    QAction* FileSaveAs;
    QAction* FileOpen;
    QStatusBar* StatusBar;

};

void MyMainWindow::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        MyLabel->move(event->x(), event->y());
        a=MyLabel->x();
        b=MyLabel->y();
    }
}

void MyMainWindow::keyPressEvent(QKeyEvent *event) {
    switch( event->key() ){
        case Qt::Key_Left: MyLabel->move(MyLabel->pos().x()-1,MyLabel->pos().y());
        a=MyLabel->x();
        b=MyLabel->y();
            break;
        case Qt::Key_Right: MyLabel->move(MyLabel->pos().x()+1,MyLabel->pos().y());
        a=MyLabel->x();
        b=MyLabel->y();
            break;
        case Qt::Key_Up: MyLabel->move(MyLabel->pos().x(),MyLabel->pos().y()-1);
        a=MyLabel->x();
        b=MyLabel->y();
            break;
        case Qt::Key_Down: MyLabel->move(MyLabel->pos().x(),MyLabel->pos().y()+1);
        a=MyLabel->x();
        b=MyLabel->y();
        break;
}
}


MyMainWindow::MyMainWindow() {
    MyLabel = new QLabel(this);
    MyLabel->setText("Hello World!");
    MyLabel->move(10, 20);
    QString xxx;
    a=MyLabel->x();
    b=MyLabel->y();
     //(*String)=MyLabel->text();

     xxx=MyLabel->text();
    //int duzina=xxx.length();
    String=&xxx;
    int duzina=(*String).length();

    FileSaveAs = new QAction(tr("&Save As..."), this);
    FileSaveAs->setShortcut(tr("CTRL+S"));
    connect(FileSaveAs, &QAction::triggered, this,&MyMainWindow::FileSaveAsMenu);

    FileOpen = new QAction(tr("&Open..."), this);
    FileOpen->setShortcut(tr("CTRL+O"));
    connect(FileOpen, &QAction::triggered, this,&MyMainWindow::FileOpenMenu);

    FileMenu = menuBar()->addMenu(tr("&File"));
    FileMenu->addAction(FileSaveAs);
    FileMenu->addAction(FileOpen);

    EditNoviTekst = new QAction(tr("&Novi tekst..."), this);
    EditNoviTekst->setShortcut(tr("CTRL+N"));
    connect(EditNoviTekst, &QAction::triggered, this,&MyMainWindow::EditNoviTekstMenu);

    EditMenu = menuBar()->addMenu(tr("&Edit"));
    EditMenu->addAction(EditNoviTekst);



    QStatusBar *statusBar = this->statusBar();


    QLabel *coord = new QLabel( tr("  Pozicija  ") );
    QLabel *length = new QLabel( tr(" Duzina  ") );




    coord->setMinimumSize( coord->sizeHint() );
    coord->setAlignment( Qt::AlignCenter );
    //coord->setText(QString::number(MyLabel->x())+","+QString::number(MyLabel->y()));
    coord->setText(QString::number(a)+","+QString::number(b));
    coord->setToolTip( tr("Koordinate teksta."));

    statusBar->addPermanentWidget( coord );

    length->setMinimumSize( length->sizeHint() );
    length->setAlignment( Qt::AlignCenter );


    length->setText(QString::number(duzina));

    length->setToolTip( tr("Govori nam duzinu teksta..."));

    statusBar->addWidget( length );
    statusBar->showMessage( tr("Ready"), 500 );

}
void MyMainWindow::FileSaveAsMenu(){
    QString fileName = QFileDialog::getSaveFileName(this,"Save As...", "", "FESB File (*.fsb)");

        if (!fileName.isEmpty()) {
            QFile file(fileName);
            if (!file.open(QIODevice::WriteOnly)) {
                QMessageBox::information(this,"Unable to Open File", file.errorString());
                return;
            }
            QTextStream out(&file);
            out << "fesb file" << endl;
            out << MyLabel->text() << endl;
            out << MyLabel->pos().x() << endl;
            out << MyLabel->pos().y() << endl;
            out << pos().x() << endl;
            out << pos().y() << endl;
            out << size().width() << endl;
            out << size().height() << endl;
        }
}
void MyMainWindow::FileOpenMenu(){
    QString fileName = QFileDialog::getOpenFileName(this,"Open Geometry...", "", "FESB File (*.fsb)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::information(this, "Unable to Open File", file.errorString());
            return;
        }
    QTextStream in(&file);
    QString str; str = in.readLine();
        if(str=="fesb file") {
            str = in.readLine();
            MyLabel->setText(str);
            int x, y, w, h;
            in >> x >> y;
            MyLabel->move(x, y);
            in >> x >> y >> w >> h;
            this->setGeometry(x, y, w, h);
        }
    }
}


void MyMainWindow::EditNoviTekstMenu() {
MyDialog dialog;
int ret = dialog.exec();
if( ret == QDialog::Accepted ) {
MyLabel->setText(dialog.lineEdit->text());
//String->append(dialog.lineEdit->text());
(*String)=dialog.lineEdit->text();
}
}

void MyMainWindow::paintEvent(QPaintEvent*){
QSize size = this->size();
QPainter painter(this);
painter.drawLine(0, size.height(), size.width(), 20);
}






int main(int argc, char **argv) {
    QApplication app (argc, argv);
    MyMainWindow mainWindow;
    mainWindow.resize(300,150);
    mainWindow.show();



    return app.exec();
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Jack Jones
  • 57
  • 6
  • What's wrong with [QMainWindow::statusBar()](https://doc.qt.io/qt-5/qmainwindow.html#statusBar)? – chehrlic Jan 15 '21 at 18:51
  • @chehrlic I don't know. I don't know how to add it/which functions to use. Also I want to make it display text length and coordinates, but I have no idea how to make it. – Jack Jones Jan 15 '21 at 19:06
  • 1
    QStatusBar is a normal widget where you can place your widgets on. There is nothing different to a normal QWidget. – chehrlic Jan 15 '21 at 20:59

2 Answers2

1

From a qmainwindow: Here is a minimal sample for your MyMainWindow class:

void MyMainWindow::updateStatusBar(){
    QString statusBar_info = QString("Len:%1, x:%2, y:%2")
    .arg(MyLabel->fontMetrics().boundingRect(MyLabel->text()).width()) //text_len
    .arg(MyLabel->x())                                               //text_x
    .arg(MyLabel->y());                                              //text_y
    statusBar()->showMessage(statusBar_info);
}
SailorV
  • 26
  • 4
  • 1
    @JackJones class definition add function prototype --- class MyMainWindow : public QMainWindow { void updateStatusBar() } ### For sure it does not update alone, you need to tell it to update when you want it to change, --- void MyMainWindow::mousePressEvent(QMouseEvent* event) { updateStatusBar(); } --- void MyMainWindow::keyPressEvent(QKeyEvent *event) { updateStatusBar(); } – SailorV Jan 15 '21 at 22:54
  • But can I just assign my lineEdit (input into the string) so it automatically changes in the MyMainWindow constructor. You can see my attempts somewhere around line 219. Also can I just somehow assign my MyLabel->pos().x() and y() to integer variable and do that in keyPressEvent and mousePressEvent. I think it is easier for me to understand it like that. – Jack Jones Jan 15 '21 at 22:58
  • 1
    Here we have a function that update the statusbar every time it's called. You can't have it your way because the constructor isnt used the way you think, it shall be called only once when when we create an object not at every time when we change something else! – SailorV Jan 15 '21 at 23:17
  • Can you implement your code into mine (edit it) so I can see the whole code, because I don't know how to make these changes? – Jack Jones Jan 15 '21 at 23:25
  • 1
    Sure give me a few minutes, i ll Update my Answer. – SailorV Jan 15 '21 at 23:26
  • 1
    THANK YOU! You did it. This is all new for me so I didn't know how to implement it. Can you just explain how to make it always show and length to be character length (e.g. length = 6 letters so it displays letter 6)? – Jack Jones Jan 15 '21 at 23:34
  • 1
    Thank you so much! I spent literally hours looking at this small problem, I am new to this. You gave me more motivation to continue! – Jack Jones Jan 15 '21 at 23:45
1

I have the answer from another question you posted about this which is now deleted:

To solve the issue you have to make coord and length variables global so that they can be accessed and modified inside your other functions , here's the updated code :

#include <QApplication>
#include <QLabel>
#include <QMainWindow>
#include <QMouseEvent>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QAction>
#include <QMenu>
#include <QMenuBar>
#include <QPainter>
#include <QFileDialog>
#include <QTextStream>
#include <QStatusBar>
#include <QProgressBar>
#include <QTextEdit>

class MyDialog : public QDialog {
public:
    MyDialog();
    QVBoxLayout* mainLayout;
    QWidget* editWidget;
    QFormLayout* editLayout;
    QLineEdit* lineEdit;
    QDialogButtonBox* buttonBox;

};

MyDialog::MyDialog() {
    lineEdit = new QLineEdit;
    editLayout = new QFormLayout;
    editLayout->addRow(new QLabel(tr("Novi tekst:")), lineEdit);
    editWidget = new QWidget;
    editWidget->setLayout(editLayout);
    buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok |QDialogButtonBox::Cancel);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
    mainLayout = new QVBoxLayout;
    mainLayout->addWidget(editWidget);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);
    setWindowTitle("Promjena teksta");

}

class MyMainWindow : public QMainWindow {
public:
    MyMainWindow();
    QLabel* MyLabel;
    QMenu* EditMenu;
    QAction* EditNoviTekst;
    QLabel *coord;
    QLabel *length;
    QString* String;
    QString*poz;
    int a,b;


    void mousePressEvent(QMouseEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void paintEvent(QPaintEvent *event) override;

    void EditNoviTekstMenu();


    void FileSaveAsMenu();
    void FileOpenMenu();
    QMenu* FileMenu;
    QAction* FileSaveAs;
    QAction* FileOpen;
    QStatusBar* StatusBar;

};

void MyMainWindow::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        MyLabel->move(event->x(), event->y());
         a=MyLabel->pos().x();
         b=MyLabel->pos().y();
         coord->setText(QString::number(a)+","+QString::number(b));
    }
}

void MyMainWindow::keyPressEvent(QKeyEvent *event) {
    switch( event->key() ){
        case Qt::Key_Left: MyLabel->move(MyLabel->pos().x()-1,MyLabel->pos().y());
        a=MyLabel->pos().x()-1;
        b=MyLabel->pos().y();
        coord->setText(QString::number(a)+","+QString::number(b));
            break;
        case Qt::Key_Right: MyLabel->move(MyLabel->pos().x()+1,MyLabel->pos().y());
        a=(int)MyLabel->pos().x()+1;
        b=MyLabel->pos().y();
        coord->setText(QString::number(a)+","+QString::number(b));
            break;
        case Qt::Key_Up: MyLabel->move(MyLabel->pos().x(),MyLabel->pos().y()-1);
        a=MyLabel->pos().x();
        b=MyLabel->pos().y();
        coord->setText(QString::number(a)+","+QString::number(b));
            break;
        case Qt::Key_Down: MyLabel->move(MyLabel->pos().x(),MyLabel->pos().y()+1);
        a=MyLabel->pos().x();
        b=MyLabel->pos().y()+1;
        coord->setText(QString::number(a)+","+QString::number(b));
        break;
}
}


MyMainWindow::MyMainWindow() {
    MyLabel = new QLabel(this);
    MyLabel->setText("Hello World!");
    MyLabel->move(10, 20);
    QString xxx;
    a=MyLabel->pos().x();
    b=MyLabel->pos().y();

     //(*String)=MyLabel->text();

     xxx=MyLabel->text();
    //int duzina=xxx.length();
    String=&xxx;
    int duzina=(*String).length();


    FileSaveAs = new QAction(tr("&Save As..."), this);
    FileSaveAs->setShortcut(tr("CTRL+S"));
    connect(FileSaveAs, &QAction::triggered, this,&MyMainWindow::FileSaveAsMenu);

    FileOpen = new QAction(tr("&Open..."), this);
    FileOpen->setShortcut(tr("CTRL+O"));
    connect(FileOpen, &QAction::triggered, this,&MyMainWindow::FileOpenMenu);

    FileMenu = menuBar()->addMenu(tr("&File"));
    FileMenu->addAction(FileSaveAs);
    FileMenu->addAction(FileOpen);

    EditNoviTekst = new QAction(tr("&Novi tekst..."), this);
    EditNoviTekst->setShortcut(tr("CTRL+N"));
    connect(EditNoviTekst, &QAction::triggered, this,&MyMainWindow::EditNoviTekstMenu);

    EditMenu = menuBar()->addMenu(tr("&Edit"));
    EditMenu->addAction(EditNoviTekst);



    QStatusBar *statusBar = this->statusBar();


    coord = new QLabel( tr("  Pozicija  ") );
    length = new QLabel( tr(" Duzina  ") );




    coord->setMinimumSize( coord->sizeHint() );
    coord->setAlignment( Qt::AlignCenter );
    //coord->setText(QString::number(MyLabel->x())+","+QString::number(MyLabel->y()));
    coord->setText(QString::number(a)+","+QString::number(b));
    coord->setToolTip( tr("Koordinate teksta."));

    statusBar->addPermanentWidget( coord );

    length->setMinimumSize( length->sizeHint() );
    length->setAlignment( Qt::AlignCenter );


    length->setText(QString::number(duzina));

    length->setToolTip( tr("Govori nam duzinu teksta..."));

    statusBar->addWidget( length );
    statusBar->showMessage( tr("Ready"), 500 );

}
void MyMainWindow::FileSaveAsMenu(){
    QString fileName = QFileDialog::getSaveFileName(this,"Save As...", "", "Your File (*.ur)");

        if (!fileName.isEmpty()) {
            QFile file(fileName);
            if (!file.open(QIODevice::WriteOnly)) {
                QMessageBox::information(this,"Unable to Open File", file.errorString());
                return;
            }
            QTextStream out(&file);
            out << "fesb file" << endl;
            out << MyLabel->text() << endl;
            out << MyLabel->pos().x() << endl;
            out << MyLabel->pos().y() << endl;
            out << pos().x() << endl;
            out << pos().y() << endl;
            out << size().width() << endl;
            out << size().height() << endl;
        }
}
void MyMainWindow::FileOpenMenu(){
    QString fileName = QFileDialog::getOpenFileName(this,"Open Geometry...", "", "FESB File (*.fsb)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::information(this, "Unable to Open File", file.errorString());
            return;
        }
    QTextStream in(&file);
    QString str; str = in.readLine();
        if(str=="fesb file") {
            str = in.readLine();
            MyLabel->setText(str);
            int x, y, w, h;
            in >> x >> y;
            MyLabel->move(x, y);
            in >> x >> y >> w >> h;
            this->setGeometry(x, y, w, h);
        }
    }
}


void MyMainWindow::EditNoviTekstMenu() {
MyDialog dialog;
int ret = dialog.exec();
if( ret == QDialog::Accepted ) {
MyLabel->setText(dialog.lineEdit->text());
length->setText(QString::number(MyLabel->text().length()));

//String->append(dialog.lineEdit->text());

}
}

void MyMainWindow::paintEvent(QPaintEvent*){
QSize size = this->size();
QPainter painter(this);
painter.drawLine(0, size.height(), size.width(), 20);
}






int main(int argc, char **argv) {
    QApplication app (argc, argv);
    MyMainWindow mainWindow;
    mainWindow.resize(300,150);
    mainWindow.show();



    return app.exec();
}

At the same time there is a bunch of other variables that do not need to be global like a and b (just on a glance), there might be more. This will not impact your code speed or anything but will make it harder to maintain as it grows.

Matt Baran
  • 315
  • 2
  • 6