V
V
vvafree2017-11-07 16:41:56
Qt
vvafree, 2017-11-07 16:41:56

How to bind a function to a QButton in VS2015 QT5 C++?

Good excerpt. Can't bind a function to a button.
There are 3 files
1. main.cpp
2. other.cpp
3. header.cpp
main.cpp

#include "Header.h"
using namespace std;

int main(int argc, char *argv[])
{
  QApplication  app(argc, argv);
  QWidget win;
  QFileD ofd;
  win.setWindowTitle("Hello");
  QPushButton *ofdButton = new QPushButton("OPEN", &win);
  QPushButton *startButton = new QPushButton("START", &win);
  QPushButton *graphButton = new QPushButton("GRAPH", &win);
  QPushButton *closeButton = new QPushButton("CLOSE", &win);

  QHBoxLayout *layout = new QHBoxLayout(&win);
  layout->addWidget(ofdButton);
  layout->addWidget(startButton);
  layout->addWidget(graphButton);
  layout->addWidget(closeButton);

  QString filename;
  
  QObject::connect(ofdButton, SIGNAL(s_transmitter()), &win, SLOT(openFile(QString filename)));
  QObject::connect(closeButton, SIGNAL(clicked(bool)), &win, SLOT(close()));
  
  win.show();
  return app.exec();
}

header.cpp
#pragma once
#include <QtWidgets/QApplication>
#include <QtWidgets>
#include <QtGui>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QApplication>
#include <QFileDialog>
#include <QDebug>
#include <QString>
#include <QDialog>
#include <QHBoxLayout>

#include <iostream>


using namespace std;
using namespace cv;


class QFileD : public QWidget
{
  Q_OBJECT
public:

public slots:
  void openFile(QString filename);
signals:
  void s_transmitter();
};

other.cpp
#include "Header.h"

void QFileD::openFile(QString filename)
  {
    filename = QFileDialog::getOpenFileName(
      this,
      "Open Document",
      QDir::currentPath(),
      "All files (*.*) ;; Document files (*.doc *.rtf);; PNG files (*.png)");

    if (!filename.isNull())
    {
      qDebug() << "selected file path : " << filename.toUtf8();
    }
    emit s_transmitter();
  }

At first he scolded
signals:
  s_transmitter();

added void
signals:
  void s_transmitter();

Began to swear by krakozyabry indicating the QfileD class.
I found one solution, replace Qwidget with Yshious
class QFileD : public Qwidget
with
class QFileD : public Qobject
but all "this" began to be highlighted as incorrect.
It seems like a simple thing, attach a function to a button, but get stuck for the whole day

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vvafree, 2017-11-08
@vvafree

Everything was decided. Found in an example how to do it. https://wiki.qt.io/How_to_Use_QPushButton/en

D
devalone, 2017-11-07
@devalone

QPushButton *ofdButton = new QPushButton("OPEN", &win);
// ...
 QObject::connect(ofdButton, SIGNAL(s_transmitter()), &win, SLOT(openFile(QString filename)));

QPushButton does not have such a signal, and it should not connect to the slot that receives the string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question