0

我正在尝试切换堆叠的按钮,如下面的应用程序所示。

宣言:

#include <QPushButton>
#include <QMainWindow>
#include <QStackedWidget>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

private:
   QPushButton* m_button[2];
   QStackedWidget *m_buttonStack;
};

实施(注意连接):

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    resize(300, 300);

    m_buttonStack = new QStackedWidget( this );
    m_buttonStack->setGeometry( 100, 100 , 100 , 100 );

    m_button[0] = new QPushButton( this );
    m_button[0]->setText( "Button 1" );
    m_buttonStack->addWidget( m_button[0] );

    m_button[1] = new QPushButton( this );
    m_button[1]->setText( "Button 2" );
    m_buttonStack->addWidget( m_button[1] );

    m_buttonStack->setCurrentWidget( m_button[1] );

    QObject::connect( m_button[0] , SIGNAL( clicked() ) , m_buttonStack , SLOT( setCurrentWidget( m_button[1] ) ) );
    QObject::connect( m_button[1] , SIGNAL( clicked() ) , m_buttonStack , SLOT( setCurrentWidget( m_button[0] ) ) );
}

由于某些莫名其妙的原因,虽然QStackedWidget::setCurrentWidget定义QObject::connect无法连接到它,但从应用程序输出窗口复制的以下错误消息显示:

Object::connect: No such slot QStackedWidget::setCurrentWidget( m_button[1] ) in ..\mainwindow.cpp:21
Object::connect: No such slot QStackedWidget::setCurrentWidget( m_button[0] ) in ..\mainwindow.cpp:22
4

2 回答 2

2

你会想要使用QSignalMapper

connect(m_button[0], SIGNAL(clicked()), m_signalMapper, SLOT(map()));
m_signalMapper->setMapping(m_button[0],m_button[1]);
connect(m_button[1], SIGNAL(clicked()), m_signalMapper, SLOT(map()));
m_signalMapper->setMapping(m_button[1],m_button[0]);

QObject::connect(signalMapper , SIGNAL( mapped(QWidget *) ) , m_buttonStack , SLOT( setCurrentWidget(QWidget *) ) );
于 2013-09-10T14:17:26.420 回答
1

当引用 SLOT 宏中的函数签名时,您不需要提供实际参数:

QObject::connect( m_button[0], SIGNAL( clicked() ), m_buttonStack, SLOT( setCurrentWidget( m_button[1] ) ) );

应该是这样的:

QObject::connect( m_button[0], SIGNAL( clicked() ), m_buttonStack, SLOT( setCurrentWidget( QWidget *) ) );

如您所见,即使采用这种方式,连接也无法正常工作。我建议实现您自己的插槽(不带参数)并将您的按钮点击连接到它:

QObject::connect(m_button[0], SIGNAL(clicked()), this, SLOT(onButtonClicked()));

比,在插槽中,您可以处理点击:

void MainWindow::onButtonClicked()
{
    // Get the button clicked
    QPushButton *btn = qobject_cast<QPushButton *>(sender());
    m_buttonStack->setCurrentWidget(btn);
}

因此,您甚至可以删除您的按钮数组。

于 2013-09-10T14:12:34.943 回答