代码之家  ›  专栏  ›  技术社区  ›  Chris Camacho

为什么在为QpushButton使用自定义插槽时会收到两个单击或释放的信号?

  •  0
  • Chris Camacho  · 技术社区  · 14 年前

    这是我最初以为的主要代码是消息框,但是设置一个标签有同样的效果。

    #include <time.h>
    #include "ui_mainwindow.h"
    #include <QMessageBox>
    
    
    class MainWindow : public QWidget, private Ui::MainWindow {
        Q_OBJECT
        public:
            MainWindow(QWidget *parent = 0);
            void makeSum(void);
        private:
            int r1;
            int r2;
        private slots:
            void on_pushButton_released(void);
    };
    
    MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
        setupUi(this);
    }
    
    void MainWindow::on_pushButton_released(void) {
        bool ok;
        int a = lineEdit->text().toInt(&ok, 10);
    
        if (ok) {  
            if (r1+r2==a) {
                QMessageBox::information( this, "Sums","Correct!" ); 
            } else {
                QMessageBox::information( this, "Sums","Wrong!" ); 
            }
        } else {
            QMessageBox::information( this, "Sums","You need to enter a number" ); 
        }
        makeSum();
    }
    
    void MainWindow::makeSum(void) {
        r1 = rand() % 10 + 1;
        r2 = rand() % 10 + 1;
        label->setText(QString::number(r1));
        label_3->setText(QString::number(r2));
    }
    
    int main(int argc, char *argv[]) {
        srand ( time(NULL) );
        QApplication app(argc, argv);
        MainWindow mw;
        mw.makeSum();
        mw.show();
        return app.exec();
    }
    
    #include "main.moc"
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   chalup    14 年前

    您描述的行为通常意味着同一信号和插槽之间有两个连接。确保在setupui()中生成的“qmetaObject::ConnectSlotsByName(mainWindow);”是释放()信号和自定义插槽之间唯一的连接。

    推荐文章