Reputation: 119
I add a button from my code and not from GUI . There is no error appear when compile ,but the button cannot click. here is code:
//mainwindow.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;
};
//mainwidow.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);
}
i add singal and slots to test it,but it failure.So i didnt add code for easy to read. Thank you for your reading.
Upvotes: 1
Views: 951
Reputation: 547
You did it in a wrong order.
First you add one big push button to your QMainWindow
and then you re-init QMainWindow
' GUI with UI-form by calling ui->setupUi(this)
, it replaces your existing button with interface element from your UI file.
Try to add this extra button, to layout that exists in UI-form. For example:
ui->setupUi(this);
pushForTime=new QPushButton(this);
ui->mLayout->addWidget(pushForTime);
so it will be added to gui elements initialized from your UI-form.
Upvotes: 1
Reputation: 12931
Your button is probably under some other widget (most likely the QMainWindow
's central widget). Call ui->setupUi(this);
first in your constructor, before you initialize your button. This should fix it. You should still add the button to a layout though. Now I don't know if you've set a layout in your designer, but if you haven't, then set a layout to your mainwindow's central widget:
centralWidget()->setLayout(new QVBoxLayout);
After this just create your button like you do and add it to the layout:
centralWidget()->layout()->addWidget(pushForTime);
Upvotes: 0