我使用C ++编写QT 4.8.4编程。我想要一个下拉菜单,我可以在其中选择一个选项,然后它将运行一个带有菜单上所选项目的exe作为exe的选项。
这是我的代码:
#ifndef GUI_H
#define GUI_H
#include <QDialog>
#include <QtGui>
class QLabel;
class QLineEdit;
class QPushButton;
class gui : public QDialog
{
Q_OBJECT
public:
gui(QWidget *parent = 0);
public slots:
void gui::on_go_clicked();
private:
QLabel *label1;
QLabel *label2;
QLineEdit *lineEdit;
QPushButton *goButton;
QComboBox cb;
};
#endif
.cpp文件:
#include <QtGui>
#include <QApplication>
#include <QComboBox>
#include "gui.h"
#include <vector>
gui::gui(QWidget *parent) : QDialog(parent)
{
label1 = new QLabel(tr("Insert Name (Optional):"));
label2 = new QLabel(tr("Class Name (Required):"));
lineEdit = new QLineEdit;
goButton = new QPushButton(tr("&Go"));
goButton->setDefault(true);
connect(goButton, SIGNAL(clicked()), this, SLOT(on_go_clicked()));
QComboBox *cb = new QComboBox();
cb->addItem("Hello", "1");
cb->addItem("Test", "2");
QHBoxLayout *hLayout1 = new QHBoxLayout;
hLayout1->addWidget(label1);
hLayout1->addWidget(lineEdit);
QHBoxLayout *hLayout2 = new QHBoxLayout;
hLayout2->addWidget(label2);
hLayout2->addWidget(cb);
QHBoxLayout *hLayout3 = new QHBoxLayout;
hLayout3->addWidget(goButton);
hLayout3->addStretch();
QVBoxLayout *vLayout = new QVBoxLayout;
vLayout->addLayout(hLayout1);
vLayout->addLayout(hLayout2);
vLayout->addWidget(cb);
vLayout->addLayout(hLayout3);
setLayout(vLayout);
setWindowTitle(tr("TEST"));
setFixedHeight(sizeHint().height());
}
void gui::on_go_clicked()
{
QMessageBox::information(this, "ASDF", cb.currentText());
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
gui *stuff = new gui;
stuff->show();
return app.exec();
}
现在我只想弄清楚如何使用QComboBox,这是行不通的。我的代码编译,但是当我运行它时,我得到“Object :: connect:没有这样的插槽gui :: on_go_clicked()”
我正在完成教程所要做的事情。我无法弄清楚为什么这不起作用。
答案 0 :(得分:4)
删除gui::
:
class gui : public QDialog{
Q_OBJECT
...
public slots:
void gui::on_go_clicked();
^^^^^
Remove it
答案 1 :(得分:1)
我想知道为什么你编码甚至编译。没有'成员on_go_clicked'的额外资格。 从标题中删除on_go_clicked中的gui ::
答案 2 :(得分:1)
您有两个引用的QComboBox对象。
第一个是在班级:
class gui : public QDialog{
Q_OBJECT
public:
gui(QWidget *parent = 0);
public slots:
void gui::on_go_clicked();
private:
QLabel *label1;
QLabel *label2;
QLineEdit *lineEdit;
QPushButton *goButton;
QComboBox cb; // <<<=== class-level automatic object
};
第二个是构造函数
中存在的本地指针到QComboBox对象gui::gui(QWidget *parent) : QDialog(parent){
...
QComboBox *cb = new QComboBox(); // <<<=== function-level pointer using the same name
// as the class-level automatic object
要解决此问题,您可以将类级别对象更改为指针,然后将对象创建更改为简单赋值,而不是声明和初始化。
cb = new QComboBox();
此外,完成此操作后,您需要修改插槽,以便使用指针取消引用运算符来访问text()
函数
void gui::on_go_clicked(){
QMessageBox::information(this, "ASDF", cb->currentText());
}