Page 2 of 4 FirstFirst 1234 LastLast
Results 21 to 40 of 61

Thread: using an isntance of QSqlDatabase for connection defiinition

  1. #21
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Fixed it, I thought that was the mistake but doesn't seem to fix the issue...

    Quote Originally Posted by anda_skoa View Post
    Different capitalization in QML and C++ for the role: "tableName" vs. "TableName"

    Cheers,
    _
    still doesn't display...... run debugger and get seg fualt seems like its in my QML on my model

    If I move my tableNameComboBox() method code to main it kinda works (seems like it only show one item)... need to figure out how to properly call function instead of using code in main

    UPDATE: Looks Like it was a onCLick mouse area with my comboBox that was messing it up changed to onCurrentIndexChanged got rid of mouse area now list is showing in comboBox but thats with my code in main.cpp I would like to move it to a function call

    I just call tableNameComboBox() method in main so I dont have to have all that code in main

    so based off the table name the tableView should display the correct table. I Need to pass the table name selected in comboBox to my sqlSelect() method in my sqliteModel class (this function use the table name in sql the script to pull correct info from DB) but not quite sure how to do this

    When I call the sqlSelect form comboBox onCurrentIndexChanged I get errors, do I pass the selection to the method correctly do I need to convert to string? or something, I think parameter mismatch is issue with number of columns in database compared to number columns passed by sql or mismatch column names from sql to db?
    Qt Code:
    1. Errors accured with sql statement
    2. QSqlError("", "Parameter count mismatch", "")
    To copy to clipboard, switch view to plain text mode 

    =====main.qml=====
    Qt Code:
    1. import QtQuick 2.5
    2. import QtQuick.Layouts 1.1
    3. import QtQuick.Controls 1.3
    4. import QtQuick.Window 2.2
    5. import QtQuick.Dialogs 1.2
    6. import QtQuick.Layouts 1.1
    7. import QtQuick.Controls 1.4
    8.  
    9. Window {
    10. id: window1
    11. signal submitDateText(string text)
    12. signal submitUserNameText(string text)
    13. signal submitDatabaseTable(string text)
    14.  
    15. visible: true
    16. width: 760
    17. height: 450
    18. title: "User Event Log"
    19. Rectangle {
    20. id: comboBoxRect
    21. anchors.top: parent.top
    22. anchors.horizontalCenter: parent.horizontalCenter
    23. Label {
    24. id: comboLabel
    25. x: -181
    26. y: 13
    27. width: 150
    28. height: 25
    29. text: qsTr("Select Database/Date")
    30. verticalAlignment: Text.AlignVCenter
    31. }
    32. ComboBox {
    33. id: dataBaseComboBox
    34. x: 0
    35. width: 181
    36. height: 25
    37. anchors.top: parent.top
    38. anchors.topMargin: 13
    39. model: tableNameModel
    40. textRole: "tableName"
    41. onCurrentIndexChanged: {
    42. sqliteModel.sqlSelect(currentIndex);
    43. }
    44. }
    45. }
    46. TableView {
    47. width: 750;
    48. height: 350;
    49. anchors.centerIn: parent;
    50. horizontalScrollBarPolicy: 0
    51. frameVisible: true
    52. model: sqliteModel
    53. //sortIndicatorColumn : 1
    54. //sortIndicatorVisible: true
    55. TableViewColumn {
    56. role: "id"
    57. title: "id"
    58. width: 100
    59. }
    60. TableViewColumn {
    61. role: "userName"
    62. title: "User Name"
    63. width: 200
    64. }
    65. TableViewColumn {
    66. role: "eventMessage"
    67. title: "Event Message"
    68. width: 200
    69. }
    70. TableViewColumn {
    71. role: "dateTime"
    72. title: "Date Time"
    73. width: 200
    74. }
    75. }
    76. RowLayout {
    77. id: searchRowLayout
    78. x: 201
    79. y: 403
    80. anchors.horizontalCenter: parent.horizontalCenter;
    81. anchors.bottom: parent.bottom
    82. width: 750
    83. height: 47;
    84. clip: false
    85. opacity: 0.9
    86. Button {
    87. id: load_btn
    88. text: qsTr("Load")
    89. MouseArea{
    90. anchors.fill: parent
    91. onClicked: {
    92. //sqliteModel.sqlSelect(tableName);
    93. }
    94. }
    95. }
    96. Label {
    97. id: userNameLabel
    98. text: qsTr("User Name")
    99. }
    100. TextField {
    101. id: userNameTextField
    102. placeholderText: qsTr("User Name")
    103. }
    104. Label {
    105. id: dateLabel
    106. width: 25
    107. height: 15
    108. text: qsTr("Date")
    109. }
    110. TextField {
    111. id: dateTextField
    112. width: 125
    113. height: 25
    114. placeholderText: qsTr("mm//dd/yyyy")
    115. }
    116. Button {
    117. id: searchBtn
    118. text: qsTr("Search")
    119. MouseArea{
    120. anchors.fill: parent
    121. onClicked: {
    122. //---emit the submitDateText & submitUserNameText signal---//
    123. //sqliteModel.searchDateText(dateTextField.text);
    124. //sqliteModel.searchUserNameText(userNameTextField.text);
    125. //sqliteModel.deleteDailyTable();
    126. }
    127. }
    128. }
    129. Button {
    130. id: exit_btn
    131. text: qsTr("Exit")
    132. MouseArea{
    133. anchors.fill: parent
    134. onClicked: close();
    135. }
    136. }
    137. }
    138. }
    To copy to clipboard, switch view to plain text mode 

    =====main.cpp=====
    Qt Code:
    1. #include <QGuiApplication>
    2. #include <QQmlApplicationEngine>
    3. #include <QSqlDatabase>
    4. #include <QAbstractTableModel>
    5. #include <QAbstractItemModel>
    6. #include <QUrl>
    7. #include "sqlitemodel.h"
    8. #include "sortproxyfilter.h"
    9. #include "databasetables.h"
    10.  
    11.  
    12. int main(int argc, char *argv[])
    13. {
    14. QGuiApplication app(argc, argv);
    15.  
    16. sqliteModel *model = new sqliteModel;
    17.  
    18. dataBaseTables *model2 = new dataBaseTables;
    19.  
    20. model2->tableNameComboBox();
    21.  
    22. QQmlApplicationEngine engine;
    23. QQmlContext *contxt = engine.rootContext();
    24. contxt->setContextProperty("sqliteModel", model);
    25. contxt->setContextProperty("tableNameModel", model2);
    26. engine.load(QUrl("qrc:/main.qml"));
    27.  
    28. return app.exec();
    29. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 31st August 2016 at 23:41.

  2. #22
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    I might have missed it but have you posted the code for the sqlSelect method somewhereß

    Cheers,
    _

  3. #23
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    yeah I think I did but ill put up latest version, I don't Think I'm getting the variable into the sql script correctly?

    ====sqliteModel.cpp=======
    Qt Code:
    1. #include <QAbstractTableModel>
    2. #include <QSortFilterProxyModel>
    3. #include "sqlitemodel.h"
    4.  
    5. sqliteModel::sqliteModel(QObject *parent):QAbstractListModel(parent){
    6.  
    7. }
    8.  
    9. sqliteModel::~sqliteModel(){
    10.  
    11. }
    12.  
    13. int sqliteModel::rowCount(const QModelIndex &parent) const{
    14. Q_UNUSED(parent);
    15. return m_msgList.count();
    16. qDebug()<< m_msgList.count();
    17. }
    18.  
    19. QHash<int, QByteArray> sqliteModel::roleNames() const{
    20. QHash<int, QByteArray> roleNames;
    21. roleNames.insert(idRole, "id");
    22. roleNames.insert(nameRole, "userName");
    23. roleNames.insert(msgRole, "eventMessage");
    24. roleNames.insert(dateRole, "dateTime");
    25. qDebug()<< roleNames;
    26. return roleNames;
    27. }
    28.  
    29. QVariant sqliteModel::data(const QModelIndex &index, int role) const{
    30. if (index.row() < 0 || index.row() >= m_msgList.count()){
    31. return QVariant();
    32. }
    33.  
    34. QVariant text;
    35.  
    36. if(role == idRole){
    37. userEventLogMsg msg = m_msgList[index.row()];
    38. text = msg.id;
    39. qDebug() << text;
    40. }
    41. else if(role == nameRole){
    42. userEventLogMsg msg = m_msgList[index.row()];
    43. text = msg.username;
    44. qDebug() << text;
    45. }
    46. else if(role == msgRole){
    47. userEventLogMsg msg = m_msgList[index.row()];
    48. text = msg.eventmessage;
    49. qDebug() << text;
    50. }
    51. if(role == dateRole){
    52. userEventLogMsg msg = m_msgList[index.row()];
    53. text = msg.datetime;
    54. qDebug() << text;
    55. }
    56. return text;
    57. }
    58.  
    59. void sqliteModel::addEvent(const userEventLogMsg &msg){
    60. beginInsertRows(QModelIndex(), 0, 0);
    61. m_msgList.insert(0, msg);
    62. endInsertRows();
    63. }
    64.  
    65. void sqliteModel::dbConnect(){
    66.  
    67. if(!m_selectDataBase.isValid()){
    68. qDebug() << "error in opening DB";
    69. m_selectDataBase = QSqlDatabase::addDatabase("QSQLITE", "conn2");
    70. m_selectDataBase.setDatabaseName("/home/amet/userLog.db");
    71. }
    72. else{
    73. qDebug() <<"connected to DB" ;
    74. }
    75. m_selectDataBase.open();
    76. }
    77. void sqliteModel::sqlSelect(QString tableName){
    78.  
    79. dbConnect();
    80.  
    81. if(!m_selectDataBase.open()){
    82. qDebug() << "database was closed";
    83. m_selectDataBase.open();
    84. }
    85. else{
    86. qDebug() << "database is open";
    87. }
    88.  
    89. QSqlQuery selectQuery(m_selectDataBase);
    90. selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM "+tableName+";");
    91. selectQuery.addBindValue(tableName);
    92.  
    93. if(selectQuery.exec()){
    94. qDebug()<<"sql statement exicuted fine";
    95. }
    96. else{
    97. qDebug() << "Errors accured with sql statement";
    98. qDebug() << selectQuery.lastError();
    99. }
    100.  
    101. userEventLogMsg msg;
    102.  
    103. while (selectQuery.next()){
    104. msg.id = selectQuery.value(0).toString();
    105. msg.username = selectQuery.value(1).toString();
    106. msg.eventmessage = selectQuery.value(2).toString();
    107. msg.datetime = selectQuery.value(3).toString();
    108. addEvent(msg);
    109. }
    110. m_selectDataBase.close();
    111. }
    112.  
    113.  
    114. void sqliteModel::createDailyTable(QString tableName)
    115. {
    116. dbConnect();
    117. QSqlQuery createTableQry(m_selectDataBase);
    118. QString date = QDate::currentDate().toString();
    119. createTableQry.prepare("CREATE TABLE userlogevents"+date+"AS SELECT * FROM ? WHERE 0");
    120. createTableQry.addBindValue(tableName);
    121. createTableQry.exec();
    122. m_selectDataBase.close();
    123. }
    124.  
    125. void sqliteModel::deleteDailyTable(QString tableName)
    126. {
    127. dbConnect();
    128.  
    129. //--- If the table is older than 30 days drop it---//
    130. QSqlQuery deleteTableQry(m_selectDataBase);
    131. deleteTableQry.prepare("DROP TABLE ?");
    132. deleteTableQry.addBindValue(tableName);
    133. if(deleteTableQry.exec()){
    134. qDebug()<<"sql statement exicuted fine";
    135. }
    136. else{
    137. qDebug() << "Errors accured with sql statement";
    138. qDebug() << deleteTableQry.lastError();
    139. }
    140. m_selectDataBase.close();
    141. }
    142.  
    143. void sqliteModel::searchDateText(const QString &dateText)
    144. {
    145. qDebug() << "c++: sqliteModel::searchDateText:" << dateText;
    146.  
    147. dbConnect();
    148.  
    149. if(!m_selectDataBase.open())
    150. {
    151. qDebug() << "database was closed";
    152. m_selectDataBase.open();
    153. }
    154. else{
    155. qDebug() << "database is open";
    156. }
    157.  
    158. QSqlQuery selectQuery(m_selectDataBase);
    159. selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents WHERE dateText = ?");
    160. selectQuery.addBindValue(dateText);
    161.  
    162.  
    163. if(selectQuery.exec()){
    164. qDebug()<<"sql statement exicuted fine";
    165. }
    166. else{
    167. qDebug() << "Errors accured with sql statement";
    168. qDebug() << selectQuery.lastError();
    169. }
    170.  
    171. userEventLogMsg msg;
    172.  
    173. while (selectQuery.next()){
    174. msg.id = selectQuery.value(0).toString();
    175. msg.username = selectQuery.value(1).toString();
    176. msg.eventmessage = selectQuery.value(2).toString();
    177. msg.datetime = selectQuery.value(3).toString();
    178. addEvent(msg);
    179. }
    180. m_selectDataBase.close();
    181. }
    182.  
    183. void sqliteModel::searchUserNameText(const QString &userNameText)
    184. {
    185. qDebug() << "c++: sqliteModel::searchUserNameText:" << userNameText;
    186.  
    187. dbConnect();
    188.  
    189. if(!m_selectDataBase.open())
    190. {
    191. qDebug() << "database was closed";
    192. m_selectDataBase.open();
    193. }
    194. else{
    195. qDebug() << "database is open";
    196. }
    197.  
    198. QSqlQuery selectQuery(m_selectDataBase);
    199. selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents WHERE userName = ?");
    200. selectQuery.addBindValue(userNameText);
    201.  
    202.  
    203. if(selectQuery.exec()){
    204. qDebug()<<"sql statement exicuted fine";
    205. }
    206. else{
    207. qDebug() << "Errors accured with sql statement";
    208. qDebug() << selectQuery.lastError();
    209. }
    210.  
    211. userEventLogMsg msg;
    212.  
    213. while (selectQuery.next()){
    214. msg.id = selectQuery.value(0).toString();
    215. msg.username = selectQuery.value(1).toString();
    216. msg.eventmessage = selectQuery.value(2).toString();
    217. msg.datetime = selectQuery.value(3).toString();
    218. addEvent(msg);
    219. }
    220. m_selectDataBase.close();
    221. }
    To copy to clipboard, switch view to plain text mode 

    ======sqliteModel.h=======
    Qt Code:
    1. #ifndef SQLITEMODEL_H
    2. #define SQLITEMODEL_H
    3.  
    4. #include <assert.h>
    5. #include <list>
    6. #include <QList>
    7. #include <QColor>
    8. #include <QObject>
    9. #include <QDebug>
    10. #include <QString>
    11. #include <QFileInfo>
    12. #include <QDateTime>
    13. #include <QQmlError>
    14. #include <QQmlApplicationEngine>
    15. #include <QQmlEngine>
    16. #include <QQmlContext>
    17. #include <QtSql/QSqlDatabase>
    18. #include <QtSql/QSqlQuery>
    19. #include <QtSql/QSqlError>
    20. #include <QtSql/QSqlRecord>
    21. #include <QModelIndex>
    22. #include <QAbstractTableModel>
    23. #include <QAbstractListModel>
    24. #include <QAbstractItemModel>
    25. #include <QListIterator>
    26.  
    27. struct userEventLogMsg{
    28. QString id;
    29. QString username;
    30. QString eventmessage;
    31. QString datetime;
    32. };
    33.  
    34. class sqliteModel:public QAbstractListModel
    35. {
    36. Q_OBJECT
    37.  
    38. public:
    39. explicit sqliteModel(QObject *parent = 0);
    40.  
    41. ~sqliteModel();
    42.  
    43. enum userEventRoles {idRole= Qt::UserRole + 220, nameRole, msgRole, dateRole};
    44.  
    45. int rowCount(const QModelIndex & parent) const;
    46.  
    47. QHash<int, QByteArray> roleNames() const;
    48.  
    49. QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const;
    50.  
    51. Q_INVOKABLE void addEvent(const userEventLogMsg &msg);
    52.  
    53. Q_INVOKABLE void dbConnect();
    54.  
    55. Q_INVOKABLE void sqlSelect(QString tableName);
    56.  
    57. Q_INVOKABLE void createDailyTable(QString tableName);
    58.  
    59. public slots:
    60.  
    61. void searchDateText(const QString &dateIn);
    62.  
    63. void searchUserNameText(const QString &userNameIn);
    64.  
    65. void deleteDailyTable(QString tableName);
    66.  
    67. private:
    68. QList<userEventLogMsg> m_msgList;
    69. QSqlDatabase m_selectDataBase;
    70. QSqlQuery m_selectQuery;
    71. };
    72.  
    73. #endif // SQLITEMODEL_H
    To copy to clipboard, switch view to plain text mode 

    ====databasetables.cpp====
    Qt Code:
    1. #include "databasetables.h"
    2.  
    3. dataBaseTables::dataBaseTables(QObject *parent):QAbstractListModel(parent){
    4.  
    5. }
    6.  
    7. dataBaseTables::~dataBaseTables(){
    8.  
    9. }
    10.  
    11. int dataBaseTables::rowCount(const QModelIndex &parent) const{
    12. Q_UNUSED(parent);
    13. return m_tableNameList.count();
    14. qDebug()<< m_tableNameList.count();
    15. }
    16.  
    17. QHash<int, QByteArray> dataBaseTables::roleNames() const{
    18. QHash<int, QByteArray> roleNames;
    19. roleNames.insert(tableNameRole, "tableName");
    20. qDebug()<< roleNames;
    21. return roleNames;
    22. }
    23.  
    24. QVariant dataBaseTables::data(const QModelIndex &index, int role) const{
    25. if (index.row() < 0 || index.row() >= m_tableNameList.count()){
    26. return QVariant();
    27. }
    28. QVariant text;
    29. if(role == tableNameRole){
    30. tableNames tables = m_tableNameList[index.row()];
    31. text = tables.tablename;
    32. qDebug() << text;
    33. }
    34. return text;
    35. }
    36.  
    37. void dataBaseTables::addTableName(const tableNames &tables){
    38. beginInsertRows(QModelIndex(), 0, 0);
    39. m_tableNameList.insert(0, tables);
    40. endInsertRows();
    41. }
    42.  
    43. void dataBaseTables::dbConnect(){
    44.  
    45. if(!m_selectTableNames.isValid()){
    46. qDebug() << "error in opening DB";
    47. m_selectTableNames = QSqlDatabase::addDatabase("QSQLITE", "conn3");
    48. m_selectTableNames.setDatabaseName("/home/amet/userLog.db");
    49. }
    50. else{
    51. qDebug() <<"connected to DB" ;
    52. }
    53. m_selectTableNames.open();
    54. }
    55.  
    56. void dataBaseTables::tableNameComboBox(){
    57. dbConnect();
    58. QSqlQuery selectTables(m_selectTableNames);
    59.  
    60. //---Selects all tables older than 30 days in database | Gets date created---//
    61. selectTables.prepare("SELECT name FROM sqlite_master WHERE type='table';");
    62.  
    63. if(selectTables.exec()){
    64. qDebug()<<"sql statement exicuted fine";
    65. }
    66. else{
    67. qDebug() << "Errors accured with sql statement";
    68. qDebug() << selectTables.lastError();
    69. }
    70.  
    71. tableNames tables;
    72. QString tableNameResults;
    73.  
    74. while (selectTables.next()){
    75. tables.tablename = selectTables.value(0).toString();
    76. tableNameResults = selectTables.value(0).toString();
    77. qDebug() << "Table Results: "+tableNameResults;
    78. addTableName(tables);
    79. }
    80. m_selectTableNames.close();
    81. //return tableNameResults;
    82. }
    To copy to clipboard, switch view to plain text mode 


    ====databasetables.h=====
    Qt Code:
    1. #ifndef DATABASETABLES_H
    2. #define DATABASETABLES_H
    3.  
    4. #include <QString>
    5. #include <QDebug>
    6. #include <QQmlContext>
    7. #include <QtSql/QSqlDatabase>
    8. #include <QtSql/QSqlQuery>
    9. #include <QtSql/QSqlError>
    10. #include <QtSql/QSqlRecord>
    11. #include <QModelIndex>
    12. #include <QSqlDatabase>
    13. #include <QAbstractListModel>
    14. #include <QAbstractItemModel>
    15.  
    16. struct tableNames{
    17. QString tablename;
    18. };
    19.  
    20. class dataBaseTables: public QAbstractListModel
    21. {
    22. Q_OBJECT
    23.  
    24. public:
    25. explicit dataBaseTables(QObject *parent = 0);
    26.  
    27. ~dataBaseTables();
    28.  
    29. enum dataTableNameRoles {tableNameRole= Qt::UserRole + 220};
    30.  
    31. int rowCount(const QModelIndex & parent) const;
    32.  
    33. QHash<int, QByteArray> roleNames() const;
    34.  
    35. QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const;
    36.  
    37. Q_INVOKABLE void addTableName(const tableNames &tables);
    38.  
    39. Q_INVOKABLE void dbConnect();
    40.  
    41. Q_INVOKABLE void tableNameComboBox();
    42.  
    43. public slots:
    44.  
    45. private:
    46. QList<tableNames> m_tableNameList;
    47. QSqlDatabase m_selectTableNames;
    48. QSqlQuery m_tableNamesQuery;
    49. };
    50. #endif // DATABASETABLES_H
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 31st August 2016 at 23:48.

  4. #24
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    That looks mostly ok, I only saw

    - in sqliteModel::sqlSelect() you have a addBindValue() but no parameter in the query

    - you are always adding to the model's list, but maybe that is what you want

    Cheers,
    _

  5. #25
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    I'm not sure the proper way to pass the tableName variable into the sql script ? I thought that when you do pass a variable you must bind the value I thought that it would be mainly for update scripts however I figure I would see if that had any affect on exec the script... any suggestions ? I get little confused cause its not a WHERE statement its FROM and not sure if I'm setting up the sql script correctly...

    Update: I added a debug statement in my sqlSelect() method to see what the tableName was passing in, and its an int value. I call the sqlSelect() method in the qml, I want to pass the text of the selected item I thought currentIndex would do that but after reading the documentation its an int value and thats not what I want todo

    dug around the documentation and found currentText() should work lol I'll try this and see if it works and it dose

    after reading around It seems like sqlite_master table doesn't store the create_date

    need to append a current Date to table name when creating them... not sure if this is possible with sqlite saw a couple post that advise this is a bad away of doing it but it seems like a good logical way to do this task.

    Task: Create user log event system.

    What I have come up with:
    -Create a database to store user log events (sqlite)
    -created a global function to push user event messages to a database table throughout the app
    -still need to figure out how to push to each daily table (pass tableName as parameter in sql script)
    -create a table for every day to store daily user events
    -use the curren date determine if you need to create a table for the current day
    -use the date the table was created and if its older than 30 days (archive it instead of dropping not sure if sqlite supports archiving)
    -search threw daily table by userName and possible dateTime
    -created a drop down list that gets data from a model to display table names in the database to select different tables (by date) to display in the tableView based of the tablName passed to the fcn

    Qt Code:
    1. onCurrentIndexChanged: {
    2. sqliteModel.sqlSelect(currentText);
    3. }
    To copy to clipboard, switch view to plain text mode 


    Added after 7 minutes:


    "- you are always adding to the model's list, but maybe that is what you want"

    I see what you mean by always adding to the list, thats not what I want to-do. I need it to restart the list or model but unsure how to do that... is there a list Clear() method I can call?


    Added after 45 minutes:


    Been working on my deleteDailyTable() function need some help comparing date of table created and currentDate minus 30days. I think I got the current date minus 30 days set to a variable to check in an if() condition. I'm having trouble getting the date of the table set to variable to compare to currentDate minus 30days....

    Qt Code:
    1. void sqliteModel::deleteDailyTable()
    2. {
    3. dbConnect();
    4. QSqlQuery deleteTableQry(m_selectDataBase);
    5. QSqlQuery tableListQry(m_selectDataBase);
    6. tableListQry.prepare("SELECT name FROM sqlite_master WHERE DATEDIFF(day, create_date, getdate()) > 10");
    7. tableListQry.exec();
    8.  
    9. //---get the number of rows---//
    10. int numberOfRows = 0;
    11. if(tableListQry.last())
    12. {
    13. numberOfRows = tableListQry.at() + 1;
    14. tableListQry.first();
    15. tableListQry.previous();
    16. }
    17. qDebug() << "number of rows: "+numberOfRows;
    18.  
    19. //---Populate sql results in array---//
    20. while(tableListQry.next()) {
    21. for(int i =0; i<=numberOfRows; i++)
    22. {
    23. //---store the information in a array---//
    24. QString results[numberOfRows];
    25. results[i] = tableListQry.value(i).toString();
    26. qDebug() << "results: "+results[i];
    27. }
    28. }
    29.  
    30. //---get current date minus 30days---//
    31. QDate deleteDate = QDate::currentDate().addDays(-30);
    32. qDebug() << "deleteDate: "+deleteDate.toString();
    33.  
    34. //---get table date---//
    35. QDate tableDate;
    36. //tableDate = results[0];
    37.  
    38. //--- If the table is older than 30 days drop it---//
    39. if(deleteDate == tableDate){
    40. deleteTableQry.prepare("DROP TABLE tableName");
    41. if(deleteTableQry.exec()){
    42. qDebug()<<"sql statement exicuted fine";
    43. }
    44. else{
    45. qDebug() << "Errors accured with sql statement";
    46. qDebug() << deleteTableQry.lastError();
    47. }
    48. }
    49. m_selectDataBase.close();
    50. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 1st September 2016 at 18:49.

  6. #26
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Quote Originally Posted by jfinn88 View Post
    "- you are always adding to the model's list, but maybe that is what you want"

    I see what you mean by always adding to the list, thats not what I want to-do. I need it to restart the list or model but unsure how to do that... is there a list Clear() method I can call?
    See comment #16

    Quote Originally Posted by jfinn88 View Post
    Been working on my deleteDailyTable() function need some help comparing date of table created and currentDate minus 30days.
    Qt Code:
    1. QDate date = QDate::currentDate().addDays(-30);
    To copy to clipboard, switch view to plain text mode 

    Cheers,
    _

  7. #27
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    I was able to figure this part out wasn’t hard, I updated the code after I figured it out

    Qt Code:
    1. QDate date = QDate::currentDate().addDays(-30);
    To copy to clipboard, switch view to plain text mode 

    When back looked a post #16 implemented as is refreshing on username search!

    However running into issue with getting date table is created or concatenating current date to table name....

    after reading around It seems like sqlite_master table doesn't store the create_date

    need to append a current Date to table name when creating them... not sure if this is possible with sqlite saw a couple post that advise this is a bad away of doing it but it seems like a good logical way to do this task.

    Task: Create user log event system.

    What I have come up with:
    -Create a database to store user log events (sqlite)
    -created a global function to push user event messages to a database table throughout the app
    -still need to figure out how to push to each daily table (pass tableName as parameter in sql script)
    -create a table for every day to store daily user events
    -use the curren date determine if you need to create a table for the current day
    -use the date the table was created and if its older than 30 days (archive it instead of dropping not sure if sqlite supports archiving)
    -search threw daily table by userName and possible dateTime
    -created a drop down list that gets data from a model to display table names in the database to select different tables (by date) to display in the tableView based of the tablName passed to the fcn

    Thought about creating a table to store table names and dates created but not sure if that will work...
    Last edited by jfinn88; 1st September 2016 at 21:12.

  8. #28
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Created a new table to hold table names and table dates created.

    trying to pull from that database a stick results in an array for use in a conditional loop to check table dates however I'm running into an issue with populating my array using a for loop.

    I set my database connection using my QSqlQuery object
    Set up a model to display the daily table in a tableView in QML (expose c++ by setting context property of engine)
    set up a model for drop down box to display daily tables to change the tableView (refresh by clearing list an reset model)
    I prepare an SELECT sql script to pull data from database
    I check the qry ran correctly using an if loop
    Then I get the size of my qry (since it is sqlite can't use size() or length() to get it) using a if statement that checks last item and adds one (since it starts at 0)
    I create an array of the size of the qry
    I loop threw a for loop to populate array using sqlQry.value()
    I then create a variable to store the current date -30days
    I have commented out the part where I compare dates and drop the table from the databae (would like to change to archiving but will start off by dropping table)

    Qt Code:
    1. void sqliteModel::deleteDailyTable()
    2. {
    3. dbConnect();
    4.  
    5. QSqlQuery deleteTableQry(m_selectDataBase);
    6. QSqlQuery tableNameDateQry(m_selectDataBase);
    7.  
    8. tableNameDateQry.prepare("SELECT name, tableDate FROM tableDates");
    9.  
    10. if(tableNameDateQry.exec()){
    11. qDebug()<<"sql statement exicuted fine";
    12. }
    13. else{
    14. qDebug() << "Errors accured with sql statement";
    15. qDebug() << tableNameDateQry.lastError();
    16. }
    17.  
    18. //---get the number of rows---//
    19. //int numberOfRows = 0;
    20. //tableNameDateQry.last();
    21. //qDebug() << tableNameDateQry.at() + 1;
    22. //numberOfRows = tableNameDateQry.at() + 1;
    23.  
    24.  
    25. int numberOfRows = 0;
    26.  
    27. //---get the number of rows---//
    28. if(tableNameDateQry.exec())
    29. {
    30. tableNameDateQry.last();
    31. numberOfRows = tableNameDateQry.at()+1;
    32. qDebug() << numberOfRows;
    33. tableNameDateQry.first();
    34. tableNameDateQry.previous();
    35. }
    36.  
    37. QString results[numberOfRows];
    38.  
    39. //---Populate sql results in array---//
    40. if(tableNameDateQry.next()){
    41. qDebug() << "made it inside while loop";
    42. for(int i=0; i<=numberOfRows; i++){
    43. qDebug() << "made it inside for loop";
    44. //---store the information in a array---//
    45. results[i] = tableNameDateQry.value(i).toString();
    46. qDebug() << "results: "+results[i];
    47. }
    48. }
    49.  
    50. //---get current date minus 30days---//
    51. QDate deleteDate = QDate::currentDate().addDays(-30);
    52. qDebug() << "deleteDate: "+deleteDate.toString();
    53.  
    54. //---get table date---//
    55. //QDate tableDate;
    56. //tableDate = results[0];
    57.  
    58. //--- If the table is older than 30 days drop it---//
    59. //if(deleteDate == tableDate){
    60. //deleteTableQry.prepare("DROP TABLE tableName");
    61. //if(deleteTableQry.exec()){
    62. //qDebug()<<"sql statement exicuted fine";
    63. //}
    64. //else{
    65. //qDebug() << "Errors accured with sql statement";
    66. //qDebug() << deleteTableQry.lastError();
    67. //}
    68. //}
    69. //m_selectDataBase.close();
    70. }
    To copy to clipboard, switch view to plain text mode 

    I'm not sure if I'm setting the size of my array correctly also it runs into a seg fault after completing for loop. only the first two items from the query get populated into array the rest don't

    update: setting the condition of the for loop upper bound <= seems to cause program to crash changed to just < array still only gets the first row of sql qry results...

    update: I dont think an array is the way do to this going to try creating a struct to hold data of qry...
    Last edited by jfinn88; 2nd September 2016 at 23:49.

  9. #29
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    C++ can't create a plain array with a size that is unknown at compile time.

    In fact that could should not have compiled at all.

    But you don't need an array, just use a QStringList and append to it in the normal query "next" loop.

    Btw, you seem to be executing the "tableNameDateQry" twice (line 10 and line 28), for no apparent reason.

    Cheers,
    _

  10. The following user says thank you to anda_skoa for this useful post:

    jfinn88 (6th September 2016)

  11. #30
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    anda_skoa,

    I have migrated away from using multiple tables it seems I’m able to do everything I need with just one table.

    What I would like to implement now is searching by date range. I have added to calendars to my QML one for a begin date and one for an end date, I need to pass both parameters to a function in c++ but not sure how to emit two signals to one slot so I can pass both parameters

    I have creaeted a function in c++

    =====header file========
    Qt Code:
    1. public slots:
    2. void searchDateRange(QString &beginDate, QString &endDate);
    To copy to clipboard, switch view to plain text mode 

    ======c++ file=====
    Qt Code:
    1. void sqliteModel::searchDateRange(QString &beginDate, QString &endDate)
    2. {
    3. qDebug() << "c++: sqliteModel::searchDateRange beginDate:" << beginDate;
    4. qDebug() << "c++: sqliteModel::searchDateRange endDate:" << endDate;
    5. dbConnect();
    6.  
    7. if(!m_selectDataBase.open())
    8. {
    9. qDebug() << "database was closed";
    10. m_selectDataBase.open();
    11. }
    12. else{
    13. qDebug() << "database is open";
    14. }
    15.  
    16. QSqlQuery selectQuery(m_selectDataBase);
    17. selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents WHERE dateTime BETWEEN ? and ?");
    18. selectQuery.addBindValue(beginDate);
    19. selectQuery.addBindValue(endDate);
    20.  
    21.  
    22. userEventLogMsg msg;
    23. beginResetModel();
    24. m_msgList.clear();
    25. while (selectQuery.next()){
    26. msg.id = selectQuery.value(0).toString();
    27. msg.username = selectQuery.value(1).toString();
    28. msg.eventmessage = selectQuery.value(2).toString();
    29. msg.datetime = selectQuery.value(3).toString();
    30. addEvent(msg);
    31. }
    32. endResetModel();
    33. m_selectDataBase.close();
    34. }
    To copy to clipboard, switch view to plain text mode 

    ===qml=====
    Qt Code:
    1. import QtQuick 2.5
    2. import QtQuick.Layouts 1.1
    3. import QtQuick.Controls 1.3
    4. import QtQuick.Window 2.2
    5. import QtQuick.Dialogs 1.2
    6. import QtQuick.Layouts 1.1
    7. import QtQuick.Controls.Styles 1.2
    8.  
    9. Window {
    10. id: window1
    11. signal submitDateText(string text)
    12. signal submitUserNameText(string text)
    13. signal submitDatabaseTable(string text)
    14. signal submitBeginEndDate(string beginDate, string endDate)
    15. //signal submitEndDate(string text)
    16. visible: true
    17. width: 1050
    18. height: 600
    19. title: "User Event Log"
    20. ColumnLayout {
    21. id: calendarColumnLayout
    22. x: 8
    23. y: 54
    24. width: 259
    25. height: 540
    26. Rectangle {
    27. id: calendarRect1
    28. width: 247
    29. height: 247
    30. anchors.top: parent.top
    31. Calendar {
    32. id: calendar1
    33. width: 247
    34. height: 247
    35. anchors.rightMargin: -11
    36. anchors.bottomMargin: -8
    37. anchors.leftMargin: 2
    38. anchors.topMargin: 8
    39. anchors.fill: parent
    40. anchors.top: parent.top
    41. style: CalendarStyle {
    42. dayDelegate: Item {
    43. Rectangle {
    44. id: rect1
    45. anchors.fill: parent
    46. Label {
    47. id: dayDelegateText1
    48. text: styleData.date.getDate()
    49. anchors.centerIn: parent
    50. horizontalAlignment: Text.AlignRight
    51. font.pixelSize: Math.min(parent.height/3, parent.width/3)
    52. color: styleData.selected ? "red" : "black"
    53. font.bold: styleData.selected
    54. }
    55. MouseArea {
    56. anchors.horizontalCenter: parent.horizontalCenter
    57. anchors.verticalCenter: parent.verticalCenter
    58. width: styleData.selected ? parent.width / 2 : 0
    59. height: styleData.selected ? parent.height / 2 : 0
    60. Rectangle {
    61. anchors.fill: parent
    62. color: "transparent"
    63. border.color: "darkorange"
    64. }
    65. }
    66. }
    67. }
    68. }
    69. }
    70. }
    71. Rectangle {
    72. id: calendarRect2
    73. x: 14
    74. y: 350
    75. width: 247
    76. height: 247
    77. anchors.bottomMargin: -11
    78. anchors.bottom: parent.bottom
    79. Calendar {
    80. id: calendar2
    81. width: 247
    82. height: 247
    83. anchors.rightMargin: -5
    84. anchors.bottomMargin: 28
    85. anchors.leftMargin: -5
    86. anchors.topMargin: -28
    87. anchors.fill: parent
    88. anchors.bottom: parent.bottom
    89. style: CalendarStyle {
    90. dayDelegate: Item {
    91. Rectangle {
    92. id: rect2
    93. anchors.fill: parent
    94. Label {
    95. id: dayDelegateText2
    96. text: styleData.date.getDate()
    97. anchors.centerIn: parent
    98. horizontalAlignment: Text.AlignRight
    99. font.pixelSize: Math.min(parent.height/3, parent.width/3)
    100. color: styleData.selected ? "red" : "black"
    101. font.bold: styleData.selected
    102. }
    103. MouseArea {
    104. anchors.horizontalCenter: parent.horizontalCenter
    105. anchors.verticalCenter: parent.verticalCenter
    106. width: styleData.selected ? parent.width / 2 : 0
    107. height: styleData.selected ? parent.height / 2 : 0
    108. Rectangle {
    109. anchors.fill: parent
    110. color: "transparent"
    111. border.color: "darkorange"
    112. }
    113. onClicked: {
    114. //---emit the submitBegnDate signal---//
    115. //sqliteModel.searchDateRange();
    116. }
    117. }
    118. }
    119. }
    120. }
    121. }
    122. }
    123. }
    124. Label {
    125. id: calendarLabel
    126. x: 73
    127. y: 8
    128. text: qsTr("Select Date Range")
    129. }
    130.  
    131. Label {
    132. id: endDatelabel
    133. x: 104
    134. y: 309
    135. text: qsTr("End Date")
    136. }
    137.  
    138. Label {
    139. id: beginDatelabel
    140. x: 97
    141. y: 31
    142. text: qsTr("Begin Date")
    143. }
    144. }
    To copy to clipboard, switch view to plain text mode 

  12. #31
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Quote Originally Posted by jfinn88 View Post
    What I would like to implement now is searching by date range. I have added to calendars to my QML one for a begin date and one for an end date, I need to pass both parameters to a function in c++ but not sure how to emit two signals to one slot so I can pass both parameters
    You don't need any signals at all, see comment #13

    Also you probably want these slot parameters to be "const QString&" or just "QString", i.e. you don't change the values in the slot, right?

    Cheers,
    _

  13. #32
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    you are correct I don't need to change these values will I will changed it from passing by ref.

    I want to use a date picker to select a date range to pass my function however I would like to start out a little simpler and just use two calendars. I'm confused though how to pass my function call the two dates selected from the calendar...
    below is my c++ function and my QML with two calendars

    calendar1.dayDelegateText1.text ? getDate() ?


    Qt Code:
    1. void sqliteModel::searchDateRange(QString beginDate, QString endDate){
    2. qDebug() << "c++: sqliteModel::searchDateRange beginDate:" << beginDate;
    3. qDebug() << "c++: sqliteModel::searchDateRange endDate:" << endDate;
    4. dbConnect();
    5.  
    6. if(!m_selectDataBase.open())
    7. {
    8. qDebug() << "database was closed";
    9. m_selectDataBase.open();
    10. }
    11. else{
    12. qDebug() << "database is open";
    13. }
    14.  
    15. QSqlQuery selectQuery(m_selectDataBase);
    16. selectQuery.prepare("SELECT id, userName, eventMessage, dateTime FROM userlogevents WHERE dateTime BETWEEN ? and ?");
    17. selectQuery.addBindValue(beginDate);
    18. selectQuery.addBindValue(endDate);
    19.  
    20.  
    21. userEventLogMsg msg;
    22. beginResetModel();
    23. m_msgList.clear();
    24. while (selectQuery.next()){
    25. msg.id = selectQuery.value(0).toString();
    26. msg.username = selectQuery.value(1).toString();
    27. msg.eventmessage = selectQuery.value(2).toString();
    28. msg.datetime = selectQuery.value(3).toString();
    29. addEvent(msg);
    30. }
    31. endResetModel();
    32. m_selectDataBase.close();
    33. }
    To copy to clipboard, switch view to plain text mode 

    ===QML=====
    Qt Code:
    1. import QtQuick 2.5
    2. import QtQuick.Layouts 1.1
    3. import QtQuick.Controls 1.3
    4. import QtQuick.Window 2.2
    5. import QtQuick.Dialogs 1.2
    6. import QtQuick.Layouts 1.1
    7. import QtQuick.Controls.Styles 1.2
    8.  
    9. Window {
    10. id: window1
    11. visible: true
    12. width: 1050
    13. height: 600
    14. title: "User Event Log"
    15. RowLayout {
    16. id: rowLayout1
    17. x: 303
    18. y: 8
    19. width: 736
    20. height: 36
    21. anchors.horizontalCenterOffset: 146
    22. anchors.topMargin: 8
    23. anchors.top: parent.top
    24. anchors.horizontalCenter: parent.horizontalCenter
    25. Rectangle {
    26. id: comboBoxRect
    27.  
    28. Label {
    29. id: comboLabel
    30. x: 121
    31. y: 8
    32. width: 150
    33. height: 25
    34. text: qsTr("Select Table to Display")
    35. verticalAlignment: Text.AlignVCenter
    36. }
    37. ComboBox {
    38. id: dataBaseComboBox
    39. x: 325
    40. width: 181
    41. height: 25
    42. anchors.top: parent.top
    43. anchors.topMargin: 8
    44. model: tableNameModel
    45. textRole: "tableName"
    46. onCurrentIndexChanged: {
    47. sqliteModel.sqlSelect(currentText);
    48. }
    49. }
    50. }
    51. }
    52. TableView {
    53. width: 736
    54. height: 500
    55. anchors.verticalCenterOffset: 0
    56. anchors.horizontalCenterOffset: 146
    57. anchors.centerIn: parent;
    58. horizontalScrollBarPolicy: 49
    59. frameVisible: true
    60. model: sqliteModel
    61. //sortIndicatorColumn : 1
    62. //sortIndicatorVisible: true
    63. TableViewColumn {
    64. role: "id"
    65. title: "id"
    66. width: 100
    67. }
    68. TableViewColumn {
    69. role: "userName"
    70. title: "User Name"
    71. width: 200
    72. }
    73. TableViewColumn {
    74. role: "eventMessage"
    75. title: "Event Message"
    76. width: 200
    77. }
    78. TableViewColumn {
    79. role: "dateTime"
    80. title: "Date Time"
    81. width: 200
    82. }
    83. }
    84. RowLayout {
    85. id: searchRowLayout
    86. x: 201
    87. y: 556
    88. anchors.horizontalCenter: parent.horizontalCenter;
    89. anchors.bottom: parent.bottom
    90. width: 736
    91. height: 47;
    92. anchors.horizontalCenterOffset: 146
    93. anchors.bottomMargin: -3
    94. clip: false
    95. opacity: 0.9
    96. Button {
    97. id: load_btn
    98. text: qsTr("Load")
    99. MouseArea{
    100. anchors.fill: parent
    101. onClicked: {
    102. sqliteModel.sqlSelect(dataBaseComboBox.currentText);
    103. }
    104. }
    105. }
    106. Label {
    107. id: userNameLabel
    108. text: qsTr("User Name")
    109. }
    110. TextField {
    111. id: userNameTextField
    112. placeholderText: qsTr("User Name")
    113. }
    114. Label {
    115. id: dateLabel
    116. width: 25
    117. height: 15
    118. text: qsTr("Date")
    119. }
    120. TextField {
    121. id: dateTextField
    122. width: 125
    123. height: 25
    124. placeholderText: qsTr("mm//dd/yyyy")
    125. }
    126. Button {
    127. id: searchBtn
    128. text: qsTr("Search")
    129. MouseArea{
    130. anchors.fill: parent
    131. onClicked: {
    132. //---Uses QML context to access c++ fcn---//
    133. sqliteModel.searchDateRange()
    134. }
    135. }
    136. }
    137. Button {
    138. id: exit_btn
    139. text: qsTr("Exit")
    140. MouseArea{
    141. anchors.fill: parent
    142. onClicked: close();
    143. }
    144. }
    145. }
    146.  
    147. ColumnLayout {
    148. id: calendarColumnLayout
    149. x: 8
    150. y: 54
    151. width: 259
    152. height: 540
    153. Rectangle {
    154. id: calendarRect1
    155. width: 247
    156. height: 247
    157. anchors.top: parent.top
    158. Calendar {
    159. id: calendar1
    160. width: 247
    161. height: 247
    162. anchors.rightMargin: -11
    163. anchors.bottomMargin: -8
    164. anchors.leftMargin: 2
    165. anchors.topMargin: 8
    166. anchors.fill: parent
    167. anchors.top: parent.top
    168. style: CalendarStyle {
    169. dayDelegate: Item {
    170. Rectangle {
    171. id: rect1
    172. anchors.fill: parent
    173. Label {
    174. id: dayDelegateText1
    175. text: styleData.date.getDate()
    176. anchors.centerIn: parent
    177. horizontalAlignment: Text.AlignRight
    178. font.pixelSize: Math.min(parent.height/3, parent.width/3)
    179. color: styleData.selected ? "red" : "black"
    180. font.bold: styleData.selected
    181. }
    182. MouseArea {
    183. anchors.horizontalCenter: parent.horizontalCenter
    184. anchors.verticalCenter: parent.verticalCenter
    185. width: styleData.selected ? parent.width / 2 : 0
    186. height: styleData.selected ? parent.height / 2 : 0
    187. Rectangle {
    188. anchors.fill: parent
    189. color: "transparent"
    190. border.color: "darkorange"
    191. }
    192. }
    193. }
    194. }
    195. }
    196. }
    197. }
    198. Rectangle {
    199. id: calendarRect2
    200. x: 14
    201. y: 350
    202. width: 247
    203. height: 247
    204. anchors.bottomMargin: -11
    205. anchors.bottom: parent.bottom
    206. Calendar {
    207. id: calendar2
    208. width: 247
    209. height: 247
    210. anchors.rightMargin: -5
    211. anchors.bottomMargin: 28
    212. anchors.leftMargin: -5
    213. anchors.topMargin: -28
    214. anchors.fill: parent
    215. anchors.bottom: parent.bottom
    216. style: CalendarStyle {
    217. dayDelegate: Item {
    218. Rectangle {
    219. id: rect2
    220. anchors.fill: parent
    221. Label {
    222. id: dayDelegateText2
    223. text: styleData.date.getDate()
    224. anchors.centerIn: parent
    225. horizontalAlignment: Text.AlignRight
    226. font.pixelSize: Math.min(parent.height/3, parent.width/3)
    227. color: styleData.selected ? "red" : "black"
    228. font.bold: styleData.selected
    229. }
    230. MouseArea {
    231. anchors.horizontalCenter: parent.horizontalCenter
    232. anchors.verticalCenter: parent.verticalCenter
    233. width: styleData.selected ? parent.width / 2 : 0
    234. height: styleData.selected ? parent.height / 2 : 0
    235. Rectangle {
    236. anchors.fill: parent
    237. color: "transparent"
    238. border.color: "darkorange"
    239. }
    240. onClicked: {
    241. //---call the date range fcn---//
    242. }
    243. }
    244. }
    245. }
    246. }
    247. }
    248. }
    249. }
    250. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 8th September 2016 at 16:15.

  14. #33
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    I am afraid I don't understand.

    You already call methods on your model object from QML, you just do the same for the new method.
    Something like
    Qt Code:
    1. sqliteModel.searchDateRange(calendar1.getSelectedDate(), calendar2.getSelectedDate())
    To copy to clipboard, switch view to plain text mode 

    Cheers,
    _

  15. The following user says thank you to anda_skoa for this useful post:

    jfinn88 (8th September 2016)

  16. #34
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    that is what I need thank you!

    says its not a function getSelectedDate I didn't see it in the doc either ?

    update: I think its just selectedDate trying this now

    this is working its passing the selected date from the calendar...

    Qt Code:
    1. calendar1.selectedDate
    To copy to clipboard, switch view to plain text mode 

    However I need to format the date passed... it is currently passing "Wed Sep 7 00:00:00 2016 GMT-0600" I need in format yyyy-MM-dd

    would it be best to convert format in c++ or in qml before passing (or while passing) ?

    update: format in qml ->
    Qt Code:
    1. Qt.formatDate(calendar1.selectedDate,"yyyy-MM-dd")
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 8th September 2016 at 21:57.

  17. #35
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    need help loading qml component in seperate qml file...?

    ====userEventDialog.qml=======
    Qt Code:
    1. Item {
    2. //----User Event Log Component---//
    3. Component {
    4. id: usereventcomponent
    5. Item {
    6. id:userevent_item
    7. Rectangle{
    8. id: view_rect
    9. implicitHeight: 550
    10. implicitWidth: 1100
    11. radius: 10
    12. border.width:4
    13. border.color: "black"
    14. layer.enabled: true
    15. Label {
    16. id: userEventTitle_label
    17. width: 200
    18. color: "#000000"
    19. text: qsTr("User Event Log")
    20. anchors.leftMargin: 225
    21. font.bold: true
    22. anchors.topMargin: 5
    23. anchors.top: parent.top
    24. anchors.horizontalCenter: parent.horizontalCenter
    25. font.pointSize: 22
    26. }
    27. layer.effect: DropShadow {
    28. horizontalOffset: 8
    29. verticalOffset: 8
    30. radius: 8.0
    31. samples: 16
    32. color: "#80000000"
    33. source: view_rect
    34. }
    35. gradient: Gradient {
    36. GradientStop {
    37. position: 0
    38. color: "#ffffff"
    39. }
    40.  
    41. GradientStop {
    42. position: 1
    43. color: "#262626"
    44. }
    45. }
    46. enabled: true
    47. opacity: enabled ? 1.0 : .3
    48. TableView {
    49. width: 750;
    50. height: 450;
    51. anchors.verticalCenter: parent.verticalCenter
    52. anchors.left: parent.left
    53. anchors.leftMargin: 10
    54. horizontalScrollBarPolicy: 0
    55. frameVisible: true
    56. model: UserEventLog
    57. //sortIndicatorVisible: true
    58. //sortIndicatorColumn: 1
    59. TableViewColumn {
    60. role: "id"
    61. title: "id"
    62. width: 100
    63. }
    64. TableViewColumn {
    65. role: "userName"
    66. title: "User Name"
    67. width: 100
    68. }
    69. TableViewColumn {
    70. role: "eventMessage"
    71. title: "Event Message"
    72. width: 400
    73. }
    74. TableViewColumn {
    75. role: "dateTime"
    76. title: "Date Time"
    77. width: 200
    78. }
    79. }
    80. RowLayout {
    81. id: row1
    82. //anchors.horizontalCenter: parent.horizontalCenter;
    83. anchors.bottom: parent.bottom;
    84. anchors.left: parent.left
    85. anchors.leftMargin: 10
    86. spacing: 60;
    87. width: 500
    88. height: 50;
    89. Label {
    90. id: userNameLabel
    91. width: 39
    92. height: 25
    93. color: "red";
    94. text: qsTr("User Name")
    95. }
    96. TextField {
    97. id: userNameTextField
    98. width: 125
    99. height: 5
    100. style: TextFieldStyle {}
    101. placeholderText: qsTr("User Name")
    102. }
    103. Button {
    104. id: searchBtn
    105. text: qsTr("Search")
    106. //---Sets button Formatting---//
    107. style: ButtonStyle {
    108. background: Rectangle {
    109. implicitWidth: 100
    110. implicitHeight: 30
    111. anchors.fill:parent
    112. radius: 4
    113. //---Changes butotn color when pressed--//
    114. gradient: Gradient {
    115. GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
    116. GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
    117. }
    118. //---Sets button Image---//
    119. Image{
    120. width: 16
    121. height: 16
    122. anchors.verticalCenter: parent.verticalCenter
    123. anchors.left: parent.left
    124. anchors.leftMargin: 5
    125. source:"button_ok.png"
    126.  
    127. }
    128. }
    129. }
    130. MouseArea{
    131. anchors.fill: parent
    132. onClicked: {
    133. //---Uses QML context to access c++ fcn---//
    134. //UserEventLog.searchUserNameFcn(userNameTextField.text);
    135. UserEventLog.searchDateRange(Qt.formatDate(calendar1.selectedDate,"yyyy-MM-dd"), Qt.formatDate(calendar2.selectedDate,"yyyy-MM-dd"))
    136. //UserEventLog.deleteEvent();
    137. }
    138. }
    139. }
    140. Button {
    141. id: refreshBtn
    142. text: qsTr("Refresh")
    143. //---Sets button Formatting---//
    144. style: ButtonStyle {
    145. background: Rectangle {
    146. implicitWidth: 100
    147. implicitHeight: 30
    148. anchors.fill:parent
    149. radius: 4
    150. //---Changes butotn color when pressed--//
    151. gradient: Gradient {
    152. GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
    153. GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
    154. }
    155. //---Sets button Image---//
    156. Image{
    157. width: 16
    158. height: 16
    159. anchors.verticalCenter: parent.verticalCenter
    160. anchors.left: parent.left
    161. anchors.leftMargin: 5
    162. source:"return.png"
    163.  
    164. }
    165. }
    166. }
    167. MouseArea{
    168. anchors.fill: parent
    169. onClicked: {
    170. //---Emit signal---//
    171. UserEventLog.selectEvent();
    172. userNameTextField.text = "";
    173. }
    174. }
    175. }
    176. }
    177. }
    178. }
    179. //---------------------------End of User Event Log Component-------------------------------//
    180. }
    To copy to clipboard, switch view to plain text mode 

    ========qml that access userEventDialog========
    Qt Code:
    1. //-----------Code to Load User Event Dialog qml for User Event Log Button------------//
    2. Action {
    3. id: action_userEventLogBtn
    4. enabled:!inSequence
    5. onTriggered:{
    6. //----Code to Load User Event Dialog-----//
    7. input_loader.filename = ""
    8. UserEventLog.dbConnect();
    9. UserEventLog.selectEvent();
    10. weld_view.state = "USEREVENT"
    11. onLoaded: console.log("User Event Log");
    12.  
    13. }
    14. }
    15. //----------------------------------------------------------------------//
    16.  
    17.  
    18. states: [
    19. //-----------State to load User Event Log Dialog-------------//
    20. State {
    21. name: "USEREVENT"
    22. PropertyChanges {target: mask; visible:true; z: 1;}
    23. PropertyChanges {target: input_loader; sourceComponent:userevent;}
    24. }
    25. //----------------------------------------------------------//
    26. ]
    27. Component {
    28. id: userevent
    29. UserEventDialog {
    30. id: userEventLog
    31. }
    32. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 8th September 2016 at 23:35.

  18. #36
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Quote Originally Posted by jfinn88 View Post
    However I need to format the date passed... it is currently passing "Wed Sep 7 00:00:00 2016 GMT-0600" I need in format yyyy-MM-dd

    would it be best to convert format in c++ or in qml before passing (or while passing) ?

    update: format in qml ->
    Qt Code:
    1. Qt.formatDate(calendar1.selectedDate,"yyyy-MM-dd")
    To copy to clipboard, switch view to plain text mode 
    You could also try passing it as a QDateTime instead of QString

    Quote Originally Posted by jfinn88 View Post
    need help loading qml component in seperate qml file...?

    ====userEventDialog.qml=======
    If you want to instantiate that directly then the file name needs to start with a capital U.

    Cheers,
    _

  19. #37
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    Quote Originally Posted by anda_skoa View Post
    You could also try passing it as a QDateTime instead of QString
    Okay I will give that a try...

    If you want to instantiate that directly then the file name needs to start with a capital U.

    Cheers,
    _
    I noticed that shortly after posting change file name to begin with capital now highlights purple in the editor, but nothing displays... no errors do i need to set a particular object (parent) to visible or something?

    ===UserEventDialog===
    Qt Code:
    1. Component {
    2. id: usereventcomponent
    3. UserEventDialog {
    4. id: userEventLog
    5. }
    6. }
    To copy to clipboard, switch view to plain text mode 

    =====Action to call state====
    Qt Code:
    1. Action {
    2. id: action_userEventLogBtn
    3. enabled:!inSequence
    4. onTriggered:{
    5. //----Code to Load User Event Dialog-----//
    6. input_loader.filename = "" //UserEventDialog.qml
    7. UserEventLog.dbConnect();
    8. UserEventLog.selectEvent();
    9. weld_view.state = "USEREVENT"
    10. onLoaded: console.log("User Event Log");
    11.  
    12. }
    13. }
    To copy to clipboard, switch view to plain text mode 

    ====State for component====
    Qt Code:
    1. State {
    2. name: "USEREVENT"
    3. PropertyChanges {target: mask; visible:true; z: 1;}
    4. PropertyChanges {target: input_loader; sourceComponent:usereventcomponent;}
    5. }
    To copy to clipboard, switch view to plain text mode 

    ===loader for state====
    Qt Code:
    1. Loader{
    2. id: input_loader
    3. property string filename: ""
    4. width: 950
    5. height: 500
    6. anchors.centerIn :parent
    7. sourceComponent: null
    8. z: 1
    9. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 9th September 2016 at 16:05.

  20. #38
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    As far as I can tell your loaded Item is empty.

    I.e. the root level Item in UserEventDialog.qml does not have any content.

    My guess is that you don't want that Item at all and also don't want the Component in that file, but that Component element's main Item to be the top level

    Cheers,
    _

  21. The following user says thank you to anda_skoa for this useful post:

    jfinn88 (9th September 2016)

  22. #39
    Join Date
    Jun 2016
    Posts
    99
    Thanks
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    I think the issue is in my UserEventDialog.qml but not sure what is causing it I can change the outter most object from Item to Rectangle and get a blank rectangle to display I can change the source component to a different component and it displays so issue I think is in my user event dialog component file ?

    update: issue resolved, issue was with Component object removed component object form userEventDialog .qml file works fine now

    ====UserEventDialog.qnl====
    Qt Code:
    1. Item {
    2. visible: true
    3. //----User Event Log Component---//
    4. Component {
    5. id: usereventcomponent
    6. Item {
    7. id:userevent_item
    8. Rectangle{
    9. id: view_rect
    10. implicitHeight: 550
    11. implicitWidth: 1100
    12. radius: 10
    13. border.width:4
    14. border.color: "black"
    15. layer.enabled: true
    16. Label {
    17. id: userEventTitle_label
    18. width: 200
    19. color: "#000000"
    20. text: qsTr("User Event Log")
    21. anchors.leftMargin: 225
    22. font.bold: true
    23. anchors.topMargin: 5
    24. anchors.top: parent.top
    25. anchors.horizontalCenter: parent.horizontalCenter
    26. font.pointSize: 22
    27. }
    28. layer.effect: DropShadow {
    29. horizontalOffset: 8
    30. verticalOffset: 8
    31. radius: 8.0
    32. samples: 16
    33. color: "#80000000"
    34. source: view_rect
    35. }
    36. gradient: Gradient {
    37. GradientStop {
    38. position: 0
    39. color: "#ffffff"
    40. }
    41.  
    42. GradientStop {
    43. position: 1
    44. color: "#262626"
    45. }
    46. }
    47. enabled: true
    48. opacity: enabled ? 1.0 : .3
    49. TableView {
    50. width: 750;
    51. height: 450;
    52. anchors.verticalCenter: parent.verticalCenter
    53. anchors.left: parent.left
    54. anchors.leftMargin: 10
    55. horizontalScrollBarPolicy: 0
    56. frameVisible: true
    57. model: UserEventLog
    58. //sortIndicatorVisible: true
    59. //sortIndicatorColumn: 1
    60. TableViewColumn {
    61. role: "id"
    62. title: "id"
    63. width: 100
    64. }
    65. TableViewColumn {
    66. role: "userName"
    67. title: "User Name"
    68. width: 100
    69. }
    70. TableViewColumn {
    71. role: "eventMessage"
    72. title: "Event Message"
    73. width: 400
    74. }
    75. TableViewColumn {
    76. role: "dateTime"
    77. title: "Date Time"
    78. width: 200
    79. }
    80. }
    81. RowLayout {
    82. id: row1
    83. anchors.bottom: parent.bottom;
    84. anchors.left: parent.left
    85. anchors.leftMargin: 10
    86. spacing: 60;
    87. width: 500
    88. height: 50;
    89. Label {
    90. id: userNameLabel
    91. width: 39
    92. height: 25
    93. color: "red";
    94. text: qsTr("User Name")
    95. }
    96. TextField {
    97. id: userNameTextField
    98. width: 125
    99. height: 5
    100. style: TextFieldStyle {}
    101. placeholderText: qsTr("User Name")
    102. }
    103. Button {
    104. id: searchBtn
    105. text: qsTr("Search")
    106. //---Sets button Formatting---//
    107. style: ButtonStyle {
    108. background: Rectangle {
    109. implicitWidth: 100
    110. implicitHeight: 30
    111. anchors.fill:parent
    112. radius: 4
    113. //---Changes butotn color when pressed--//
    114. gradient: Gradient {
    115. GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
    116. GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
    117. }
    118. //---Sets button Image---//
    119. Image{
    120. width: 16
    121. height: 16
    122. anchors.verticalCenter: parent.verticalCenter
    123. anchors.left: parent.left
    124. anchors.leftMargin: 5
    125. source:"button_ok.png"
    126. }
    127. }
    128. }
    129. MouseArea{
    130. anchors.fill: parent
    131. onClicked: {
    132. //---Uses QML context to access c++ fcn---//
    133. //UserEventLog.searchUserNameFcn(userNameTextField.text);
    134. UserEventLog.searchDateRange(Qt.formatDate(calendar1.selectedDate,"yyyy-MM-dd"), Qt.formatDate(calendar2.selectedDate,"yyyy-MM-dd"))
    135. //UserEventLog.deleteEvent();
    136. }
    137. }
    138. }
    139. Button {
    140. id: refreshBtn
    141. text: qsTr("Refresh")
    142. //---Sets button Formatting---//
    143. style: ButtonStyle {
    144. background: Rectangle {
    145. implicitWidth: 100
    146. implicitHeight: 30
    147. anchors.fill:parent
    148. radius: 4
    149. //---Changes butotn color when pressed--//
    150. gradient: Gradient {
    151. GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
    152. GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
    153. }
    154. //---Sets button Image---//
    155. Image{
    156. width: 16
    157. height: 16
    158. anchors.verticalCenter: parent.verticalCenter
    159. anchors.left: parent.left
    160. anchors.leftMargin: 5
    161. source:"return.png"
    162.  
    163. }
    164. }
    165. }
    166. MouseArea{
    167. anchors.fill: parent
    168. onClicked: {
    169. //---Emit signal---//
    170. UserEventLog.selectEvent();
    171. userNameTextField.text = "";
    172. }
    173. }
    174. }
    175. Button {
    176. id: exit_btn
    177. text: qsTr("Exit")
    178. //---Sets button Formatting---//
    179. style: ButtonStyle {
    180. background: Rectangle {
    181. implicitWidth: 100
    182. implicitHeight: 30
    183. anchors.fill:parent
    184. radius: 4
    185. //---Changes butotn color when pressed--//
    186. gradient: Gradient {
    187. GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
    188. GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
    189. }
    190. //---Sets button Image---//
    191. Image{
    192. width: 16
    193. height: 16
    194. anchors.verticalCenter: parent.verticalCenter
    195. anchors.left: parent.left
    196. anchors.leftMargin: 5
    197. source:"button_cancel.png"
    198. }
    199. }
    200. }
    201. MouseArea{
    202. anchors.fill: parent
    203. onClicked: weld_view.state = ""
    204. }
    205. }
    206. }
    207.  
    208. }
    209. }
    210. }
    211. //---------------------------End of User Event Log Component-------------------------------//
    212. }
    To copy to clipboard, switch view to plain text mode 
    Last edited by jfinn88; 9th September 2016 at 19:48.

  23. #40
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,396
    Thanks
    37
    Thanked 1,542 Times in 1,493 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: using an isntance of QSqlDatabase for connection defiinition

    As I said before: the Item has no content. An Item itself doesn't display anything.

    Cheers,
    _

  24. The following user says thank you to anda_skoa for this useful post:

    jfinn88 (9th September 2016)

Similar Threads

  1. Replies: 16
    Last Post: 4th September 2013, 00:49
  2. How to set x509 on a QSqlDatabase Connection?
    By m3rlin in forum Qt Programming
    Replies: 24
    Last Post: 21st February 2012, 04:04
  3. Windows OCI QSqlDatabase connection
    By hollyberry in forum Newbie
    Replies: 10
    Last Post: 13th February 2012, 22:13
  4. QSqlDatabase Connection Close on Destruction
    By Sanuden in forum Qt Programming
    Replies: 1
    Last Post: 1st September 2011, 15:32
  5. QSqlDatabase connection timeout?
    By joseprl89 in forum Qt Programming
    Replies: 6
    Last Post: 27th March 2011, 01:43

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.