我写了一个简单的代码来尝试和了解QTableView。当我构建我的项目时,它不会给出任何错误但是当我尝试运行它时说:
C:\ Users \ Eren \ Documents \ build-QTableViewUygulama-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug \ debug \ QTableViewUygulama.exe退出,代码为255
或
该程序意外结束。
C:\ Users \ Eren \ Documents \ build-QTableViewUygulama-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug \ debug \ QTableViewUygulama.exe崩溃。
我对C ++有一些了解,但我对Qt知之甚少。我不知道为什么我一直收到这个错误。这是我的代码
//Class Model(aracmodel.cpp)
#include "aracmodel.h"
AracModel::AracModel(QObject* parent = 0) : QAbstractTableModel(parent) {
}
int AracModel::rowCount(const QModelIndex &) const {
return 3;
}
int AracModel::columnCount(const QModelIndex &) const {
return Araclar.size();
}
QVariant AracModel::data(const QModelIndex &index, int role) const {
if(role != Qt::DisplayRole && role != Qt::EditRole) return 0;
const Arac& arac = Araclar[index.row()];
switch(index.column()){
case 0 : return arac.id;
case 1 : return QString::fromStdString(arac.marka);
case 2 : return QString::fromStdString(arac.model);
default : return 0;
}
return QVariant();
}
QVariant AracModel::headerData(int section, Qt::Orientation orientation, int
role){
if(orientation != Qt::Horizontal || role != Qt::DisplayRole) return 0;
switch(section){
case 0 : return "ID";
case 1 : return "Marka";
case 2 : return "Model";
default : return 0;
}
return QVariant();
}
//Class Model (aracmodel.h)
#ifndef ARACMODEL_H
#define ARACMODEL_H
#include <QAbstractTableModel>
#include "arac.h"
class Arac;
class AracModel : public QAbstractTableModel
{
public:
QList<Arac> Araclar;
AracModel(QObject*);
int rowCount(const QModelIndex&) const override;
int columnCount(const QModelIndex&) const override;
QVariant data(const QModelIndex& index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role);
};
#endif // ARACMODEL_H
//Class Header arac.h
#ifndef ARAC_H
#define ARAC_H
#include <string>
class Arac
{
public:
int id;
std::string marka;
std::string model;
Arac(int, std::string, std::string);
};
#endif // ARAC_H
Arac::Arac(int i, std::string ma, std::string mo) : id(i), marka(ma), model(mo){} //This constructor is in arac.cpp
//MainWindow.cpp (only copying the parts i've changed)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tableView->setModel(model);
}
//MainWindow.hh(only copying the parts i've changed
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
AracModel* model;
~MainWindow();
private:
Ui::MainWindow *ui;
};
答案 0 :(得分:2)
使用以下方法实例化模型指针
model = new AracModel(this);
在将此模型设置为tableView之前。
看看这个简单的例子: http://www.thedazzlersinc.com/source/2012/06/04/qt-qtableview-example-short-and-quick/