从代码添加时无法单击Qt按钮
qt button can not click when add from code
我从我的代码而不是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);
相关文章:
- 有没有办法区分Qt小部件是通过鼠标单击还是通过按表键获得焦点?
- QT - 连接 Qml 按钮 单击到 Cpp 构造函数
- 单击"推送"按钮应使用Qt C++在不同的窗口中显示绘图
- 在鼠标单击Qt时将信号从子级发送到父级
- 在图形场景Qt中右键单击Contex菜单时响应缓慢
- Qt - 右键单击时编辑按钮文本
- 在QT中单击菜单时出现隔离错误
- 在单击QT中单击图像时,尝试立即显示用户编辑操作的结果
- 如何在单击QT窗口时将键盘控件返回到QT窗口
- 模拟按钮单击qt快速控制按钮
- QT QTest::键单击或鼠标移动似乎不适用于 QMenu 在我的情况下
- 当用户单击QT中的QlineEdit时,如何更改Qlineed的文本
- Qt在单击按钮时调用Child-Window
- Ctrl 左键单击事件捕获QT
- 从代码添加时无法单击Qt按钮
- Qt:鼠标右键单击QDockWidget标题
- QT qml 按钮发出信号单击,尽管已禁用
- 忽略父 Qt 快速图像的透明区域的鼠标区域单击事件
- Qt表查看单元格中的显示图像并在单击时获取路径
- 单击QT按钮可更改明文外部编辑