I'm trying to perform action, when user clicks on button. My code is:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtUiTools/QUiLoader>
#include <QFile>
#include <QMessageBox>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
    createActions();
}

void MainWindow::test()
{
    //QMessageBox::information(this, "Welcome", "Select first image.");
    //QFileDialog::getOpenFileName(this, QT_TR_NOOP("Open Image"), "D:\\", QT_TR_NOOP("Image Files (*.png *.jpg *.bmp)"));
    resize(100,500);
}

void MainWindow::createActions()
{
    QWidget *centralWidget = this->centralWidget();
    QPushButton *buttonBack = centralWidget->findChild<QPushButton *>("pushButton");
    QObject::connect(buttonBack,SIGNAL(clicked()), this, SLOT(test()));

    QAction *open = this->findChild<QAction *>("actionOpen");
    //QMessageBox::information(this, "Welcome", open->text());

    connect(open, SIGNAL(triggered()), this, SLOT(test()));
}

Function void MainWindow::test() is defined as SLOT in header file and I'm sure, that QPushButton *buttonBack isn't null. What I'm doing wrong?

In my code I tried also to perform action through QAction, but in this case, function is performed, when I close window.

有帮助吗?

解决方案

It looks like you're setting all your actions in the destructor.

Think about what this is doing:

  1. UI starts up all happy with the setupUi() call from the constructor
  2. Throughout the lifetime of the UI, there are no buttons assigned to any slots. This means the signal from your button will never get to the slot test().
  3. Upon exit of the UI, the button is connected to the slot.

If you want this to happen, that's cool, but if you want the button to connect to the slot while the UI is running, move your createActions() function into the constructor.

Good luck!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top