看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) QT 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我想寫能下棋的程式,但是在測試點擊Button的功能時發現一個問題, 如果把button的定義(位置之類東西)跟connect都寫在mainwindow,button就有反應, 但是如果把定義跟connect寫在別的cpp檔,button可以正常顯示,但點了卻沒有反應。 預期的正確結果(Expected Output): 希望點了button之後能執行預設的動作 錯誤結果(Wrong Output): 點了沒反應 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) .h檔 #ifndef CHESS_H #define CHESS_H #include <QPushButton> #include <QWidget> #include <QObject> #include "mainwindow.h" class chess :QObject { Q_OBJECT public: chess(MainWindow *); virtual ~chess(); QPushButton *button; public slots: void buttonClick(); private: }; #endif // CHESS_H .cpp #include "chess.h" #include <QDebug> chess::chess(MainWindow *ptr) : QObject () { button = new QPushButton(ptr); button->setGeometry(565,602,70,70); //button->setIcon(QIcon(":/new/prefix1/Xiangqi_cd1.svg.png")); //button->setStyleSheet("border:none"); button->setIconSize(QSize(70, 70)); button->show(); connect(button, SIGNAL(clicked(bool)), this ,SLOT(buttonClick())); } chess::~chess() { } void chess::buttonClick() { button->move(button->x() + 20, button->y()); } mainwindow #include "mainwindow.h" #include "ui_mainwindow.h" #include <QGraphicsScene> #include <QWidget> #include <QGraphicsView> #include <QPixmap> #include <QSize> #include "chess.h" #include "bing.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->scene = new QGraphicsScene(0 ,0 ,1240 ,870); QPixmap pix(":/new/prefix1/f16693bafedd4a723abac58fca9fab17_1_-1_art.jpg"); QSize picSize(850,850); QPixmap scaledPixmap = pix.scaled(picSize, Qt::KeepAspectRatio); scene->addPixmap(scaledPixmap); ui->chessboard->setScene(this->scene); chess b(this); } MainWindow::~MainWindow() { delete ui; } 補充說明(Supplement): 希望有大大能撥空回答我QAQ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.116.116.207 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1556718689.A.1EF.html ※ 編輯: Mysterydog (49.216.158.69), 05/01/2019 21:54:27
ko27tye: 先下斷點在buttonclick()和chess建構子裡吧 看不太出來 05/01 23:23
ko27tye: 啥問題 05/01 23:23
Mysterydog: 我有用qdebug在buttonclick函式嘗試印東西,但他沒印 05/02 00:37
Mysterydog: 出來,好像沒有執行到這個函式,我在connect的上面跟 05/02 00:37
Mysterydog: 下面印都有印出來,表示有執行到這句,我覺得應該是c 05/02 00:37
Mysterydog: onnect的問題,可是我看語法也沒錯 05/02 00:37
ko27tye: 你把new QPushButton(ptr)和connect那兩行移到mainwindow 05/02 00:54
ko27tye: 內可以正常執行是嗎? 05/02 00:54
Mysterydog: 是的 05/02 01:12
Mysterydog: 而且我發現我的signal跟slot是黃色的,能正常使用的 05/02 01:15
Mysterydog: 好像都是藍色的 05/02 01:15
ko27tye: 我猜拉 可能是chess b(this); 這行 傳的是複製的this指標 05/02 01:22
ko27tye: 然後connect到的是複製的指標,建構子結束後那個複製指標 05/02 01:23
ko27tye: 也消失,然後你的connect就永遠不會發動 05/02 01:23
Mysterydog: 我找到解決方法了 在class前面加new就好了 05/02 01:52
Mysterydog: 謝謝大大的回答~ 05/02 01:53
LuisHsu: 這個程式有種熟悉的感覺......C++ 作業? 06/05 12:21