[英]Segmentation Fault while dynamicaly adding widget in Qt
我試圖在Qt中運行時添加QWidget,但是由於分段錯誤,它顯示了從OS接收到的SIGSEV信號。 這是我的代碼:
//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QtGui>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_submit_clicked();
private:
Ui::MainWindow *ui;
QLabel *label;
QLineEdit *line_edit;
};
#endif // MAINWINDOW_H
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_submit_clicked()
{
QString str = ui->lineEdit1->text();
QString str1 =ui->lineEdit2->text();
if(str=="rana"&&str1=="vivek")
{
label = new QLabel();
label->setText("Success");
MainWindow.layout->addWidget(label);
label->show();
}
else
{
line_edit = new QLineEdit();
line_edit->setText("Sorry");
MainWindow.layout->addWidget(line_edit);
line_edit->show();
}
}
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
我知道分段錯誤是由於對空指針的取消引用而發生的,但是我找不到我在哪里犯了該錯誤。
MainWindow.layout->addWidget(label);
沒什么意義-正如塞巴斯蒂安(Sebastian)所說,這甚至不應該編譯。
首先,確保您在Ui文件中具有布局(我添加了一個名為verticalLayout
垂直布局),因此您具有要在其中添加小部件的布局。 您的ui
對象中將有一個指向它的指針。
現在,只需在該布局上使用addWidget
,一切都應該工作:
void MainWindow::on_pushButton_submit_clicked()
{
QString str = ui->lineEdit1->text();
QString str1 =ui->lineEdit2->text();
if(str=="rana"&&str1=="vivek")
{
QLabel *label = new QLabel();
label->setText("Success");
ui->verticalLayout->addWidget(label);
// label->show(); widgets will became the part of the MainWindow, as the addWidget
// will add them into the hierarchy.
}
else
{
QLineEdit *line_edit = new QLineEdit();
line_edit->setText("Sorry");
ui->verticalLayout->addWidget(line_edit);
// line_edit->show()
}
}
注意addWidget
會將小部件的所有者設置為布局,因此在破壞布局時將刪除小部件。
也許以這種方式實施會有意義嗎?
void MainWindow::on_pushButton_submit_clicked()
{
QString str = ui->lineEdit1->text();
QString str1 =ui->lineEdit2->text();
QWidget *w = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout; // creates a vertical layout
if(str=="rana"&&str1=="vivek")
{
label = new QLabel(w);
label->setText("Success");
layout->addWidget(label);
}
else
{
line_edit = new QLineEdit(w);
line_edit->setText("Sorry");
layout->addWidget(line_edit);
}
w->setLayout(layout);
setCentralWidget(w);
}
更新: QMainWindow已經具有預定義的布局,因此無需引入新的布局。 上面的代碼創建一個中間小部件,並使用其自己的布局對其進行構造。 比將小部件設置為MainWindow中的中央小部件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.