[Solved] Connect combobox using signals
-
mainwindow.h
#include <QMainWindow> #include <QComboBox> #include <QWidget> #include <QPushButton> #include <QLabel> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void m_combobox(); void m_pushbutton(); private: Ui::MainWindow *ui; QComboBox *combobox; QPushButton *pushbutton; QLabel *label; }; #endif // MAINWINDOW_H
main.cpp
#include <QtGui/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); combobox = new QComboBox(); label = new QLabel("-"); combobox->addItem("AAA"); combobox->addItem("BBB"); combobox->addItem("CCC"); connect(combobox,SIGNAL (activated(int)),this,SLOT(m_combobox(int))); pushbutton= new QPushButton("My Button", this); connect(pushbutton,SIGNAL (clicked()),this,SLOT(m_pushbutton())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::m_combobox() { label->setText("1"); } void MainWindow::m_pushbutton() { }
I get only pushbutton at the output window.
-
@Ratzz Ok few problems here:
- You have not passed a parent to
QComboBox
andQLabel
so you will need to callshow()
explicitly. Pass a parent asthis
for them like you did forQPushButton
. - You have just created those widgets without assigning them a position and hence they will overlap eachother. Either use
setGeometry()
ormove()
to assign them a position or use Layouts. But using Layouts is a preferred way to do so. You can useQHBoxLayout
orQVBoxLayout
so that it takes care of positions. - The SLOTS function definition should match with that of the signal. You have missed a parameter for
QComboBox
. So it will not be able to find the slot and hence it won't work.
- You have not passed a parent to
-
@Ratzz Because in you have connected the signal
activated
to slotm_combobox
which takes one argument.
connect(combobox,SIGNAL (activated(int)),this,SLOT(m_combobox(int)));
But there is no such slot defined with single argument and thus the connection will fail as it will not be able to find that slot. You have a slotm_combobox()
which takes no arguments. -
@Ratzz pushbutton->move(10,100). See http://doc.qt.io/qt-5/qwidget.html#pos-prop
But as said earlier its best to use Layouts. See using Layouts for more details. -