-5

我在头文件私有插槽中写入,编译器给出错误:

d:\qtproject\new123\mainwindow.h:31: error: C2059: syntax error : 'public'

请帮我。我改为公共但没有区别。当我清除“公共/私人插槽”时没有错误出现,但写入加载 D:\Qtproject\new123\debug\new123.exe... QObject::connect: No such slot QPushButton:: main.cpp:18 中的 changed() QObject::connect: main.cpp:27 中没有这样的插槽 QPushButton::moved()

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
namespace Ui {
  class MainWindow;
}
class MainWindow : public QMainWindow
{
  Q_OBJECT
  public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
  private slots:
    void changed();
    void moved();
    signals:
    void clicked();
  private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"


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

}

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

void moved()
{
    QPushButton a;
     a.move(100,100);
}
void changed()

{   QPushButton g;
    g.setStyleSheet("QPushButton { background-color : white; color :blue; }");
}

main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QLabel>
#include <QPushButton>



int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    MainWindow w;

    QPushButton s("Change Color", &w);
    s.setStyleSheet("QPushButton { background-color : white; color :pink; }"
                    "QPushButton:pressed { color: blue; }");
    QObject::connect(&s, SIGNAL(clicked()), &s, SLOT(changed()));
    QPushButton d("Quit", &w);
    d.setStyleSheet("QPushButton { background-color : white; color :black; }");
    QObject::connect(&d, SIGNAL(clicked()), qApp, SLOT(quit()));
    d.move(100,0);
    QPushButton f("Move Button", &w);
    f.move(200,0);
    f.setStyleSheet("QPushButton { background-color : white; color :green; }");

    QObject::connect(&f, SIGNAL(clicked()), &f, SLOT(moved()));

    w.show();

    return a.exec();

}
4

1 回答 1

1

在学习 Qt 之前,您需要学习 C++。

您将moved()and声明changed()为 的方法MainWindow,然后在源文件中将它们定义为自由函数。然后您尝试将 连接QPushButton::clicked()到这些插槽,但告诉connect(..)方法插槽属于QPushButton而不是MainWindow

在您的moved()changed()函数中,您在每个函数中创建一个QPushButton,但不要给它们父级或将它们添加到布局中(因此它们将不可见)。您还在堆栈上创建它们,因此它们在函数结束时被销毁。

于 2015-05-08T22:06:15.017 回答