从代码添加时无法单击Qt按钮

qt button can not click when add from code

本文关键字:单击 Qt 按钮 代码 添加      更新时间:2023-10-16

我从我的代码而不是GUI中添加了一个按钮。编译时没有出现错误,但按钮无法单击。这是代码:

/

/主窗口.h

#include <QMainWindow>
#include <QtNetwork/QTcpSocket>
#include <QString>
#include <QDataStream>
#include <QByteArray>
#include <QtWidgets>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    void OnMsgSignal(const QString& tep2);
    void testForSocket();
    ~MainWindow();
    void readDataF();
private:
    Ui::MainWindow *ui;
    QString dataForTime;
    QPushButton *pushForTime;
};

主寡妇.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QWidget>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    pushForTime=new QPushButton(this);
    pushForTime->setText("点击获取时间");
    pushForTime->setGeometry(20,20,80,20);
    pushForTime->setEnabled(true);
    ui->setupUi(this);
}

我添加了单行和插槽来测试它,但它失败了。所以我没有添加易于阅读的代码。感谢您的阅读。

你做的顺序错误。

首先,您向QMainWindow添加一个大按钮,然后通过调用 ui->setupUi(this) UI 形式重新初始化QMainWindow ' GUI,它会用 UI 文件中的界面元素替换您现有的按钮。

尝试将此额外的按钮添加到 UI 形式中存在的布局中。例如:

ui->setupUi(this);
pushForTime=new QPushButton(this);
ui->mLayout->addWidget(pushForTime);

因此,它将被添加到从您的 UI 表单初始化的 GUI 元素中。

你的按钮可能在其他小部件下(很可能是QMainWindow的中心小部件(。在初始化按钮之前,首先在构造函数中调用ui->setupUi(this);。这应该可以解决它。不过,您仍应将按钮添加到布局中。现在我不知道您是否在设计器中设置了布局,但是如果您还没有,请为主窗口的中央小部件设置布局:

centralWidget()->setLayout(new QVBoxLayout);

在此之后,只需像您一样创建按钮并将其添加到布局中:

centralWidget()->layout()->addWidget(pushForTime);