How to call an object created in another function.
-
Hello
I want to call an object of class QLabel in another function . I know this is basic C++ ,but its confusing in Qt .
in my mainwindow.cpp i have created a function
void createlbl(){ QLabel *lbl1 = new QLabel("Hello"); } void Mainwindow :: resizeEvent(QResizeEvent *evt){ }
i need to call the label object (lbl1) in the resizeEvent function to resize it.
I also need to call the object in other functions in my program.
I tried different ways but i am not getting the right way to call it and use in different functions.
Please tell me what parameters should i pass and how i should call the class or the function in which the class is created to use in different functions.Thank you
-
hi
Object in other functions are not accessible to others unless used as parameter.
The trick is to declare the object in the .h file for the class.
so
QLabel *lbl1; shoud live in mainwindow.h in the class. (public)class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QLabel *lbl1; //<<<< < this is shared in all functions
};then it all works out for you.
void createlbl(){
lbl1 = new QLabel("Hello");
}void Mainwindow :: resizeEvent(QResizeEvent *evt){
lbl1 -> xxx
} -
Yes i am aware of that , but this is the problem https://forum.qt.io/topic/69999/how-to-add-a-label-on-a-layout-that-covers-the-entire-window/2
This is the reason i am using resizeEvent. -
-
but it should work. ?
show mainwindow.h
here is sample that does so
https://www.dropbox.com/s/i0qj2e9mxbggymt/mylabel.zip?dl=0 -
my mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include<QLabel> #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QLabel *lbl; protected: void resizeEvent(QResizeEvent *evt) override; private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
my mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include<QLabel> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } void MainWindow:: createlbl(){ lbl = new Qlabel(); } void MainWindow :: resizeEvent(QResizeEvent *evt) { MainWindow::setCentralWidget(lbl); lbl->setStyleSheet("Background-color:pink"); QMainWindow::resizeEvent(evt); //call base implementation } MainWindow::~MainWindow() { delete ui; }