Creating events that trigger own functions
-
hey guys I have two questions first off my code doesn't seem to be working it is telling me that MainWindow does not have a member called pushButton_2 but that is strange since I call ui->pushButton_2->setText(); above it
#include <iostream> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->pushButton->setText("hello"); ui->pushButton_2->setText("hello world 2"); std::cout << "hello from the console" << std::endl; printHello(); connect(ui->pushButton_2,SIGNAL(pressed()),ui->pushButton_2,SLOT(update())); // error } void MainWindow::printHello() { std::cout << "\n"; std::cout << "hello from printHello() function" << std::endl; delete ui; } MainWindow::~MainWindow() { delete ui; }
header
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
my second question is how do you call a function when you trigger an event say I click one of the buttons I would like my printHello() function to be called ,
sorry if I didn't format this properly couldn't find any code tags
thanks
-
Hi,
- From here it looks correct. Are you sure that in your original code both names a correct ?
By the way, why call your button update slot when you press on it ?
- Make
printHello
a slot and connect it to theclicked
signal of the push button of your choice.
-
- seems to compile now,don't know why it was not earlier
2
connect(ui->pushButton,SIGNAL(clicked()),ui->pushButton,SLOT(printHello()));
I created a slot called printHello() and used the following code,but when I click on the button nothing happens,text should appear in the console window
thanks
-
Why are you deleting ui in
printHello
?printHello
is a member of MainWindow not of your other push button.Depending on your setup, it might get shown once you end your application.
You can use
qDebug()
for your testing. -
my bad I noticed that too that is a big no no haha
yeah its strange the way printHello() isn't appearing
-
Do you have any runtime warning ?
On a side note, if you switch to the new syntax using function pointers, you'll have compile time checks rather than runtime checks for your connections.