Search Results

Search found 24 results on 1 pages for 'qvariant'.

Page 1/1 | 1 

  • How to support comparisons for QVariant objects containing a custom type?

    - by Tyler McHenry
    According to the Qt documentation, QVariant::operator== does not work as one might expect if the variant contains a custom type: bool QVariant::operator== ( const QVariant & v ) const Compares this QVariant with v and returns true if they are equal; otherwise returns false. In the case of custom types, their equalness operators are not called. Instead the values' addresses are compared. How are you supposed to get this to behave meaningfully for your custom types? In my case, I'm storing an enumerated value in a QVariant, e.g. In a header: enum MyEnum { Foo, Bar }; Q_DECLARE_METATYPE(MyEnum); Somewhere in a function: QVariant var1 = QVariant::fromValue<MyEnum>(Foo); QVariant var2 = QVariant::fromValue<MyEnum>(Foo); assert(var1 == var2); // Fails! What do I need to do differently in order for this assertion to be true? I understand why it's not working -- each variant is storing a separate copy of the enumerated value, so they have different addresses. I want to know how I can change my approach to storing these values in variants so that either this is not an issue, or so that they do both reference the same underlying variable. It don't think it's possible for me to get around needing equality comparisons to work. The context is that I am using this enumeration as the UserData in items in a QComboBox and I want to be able to use QComboBox::findData to locate the item index corresponding to a particular enumerated value.

    Read the article

  • Sorting and displaying a custom QVariant type.

    - by Kranar
    Hello, I have a custom type I'd like to use with QVariant but I don't know how to get the QVariant to display in a table or have it sort in a QSortFilterProxyModel. I register the type with Q_DECLARE_METATYPE and wrote streaming operators registered via qRegisterMetaTypeStreamOperators but for whatever reason when I use the type with a table model, it doesn't display anything and it doesn't sort. I should specify that this custom type can not be modified. It has a copy and default constructor, but I can not go in and modify the source code to get it to work with QVariant. Is there a way of non-intrusively getting the behaviour I'd like?

    Read the article

  • Accessing an enum stored in a QVariant

    - by Henry Thacker
    Hi, I have registered an enumeration type "ClefType" within my header file - this enum is registered with the MetaObject system using the Q_DECLARE_METATYPE and Q_ENUMS macros. qRegisterMetaType is also called in the class constructor. This allows me to use this type in a Q_PROPERTY, this all works fine. However, later on, I need to be able to get hold of the Q_PROPERTY of this enum type, given the object - in a form that is suitable for serialization. Ideally, it would be useful to store the integer value for that enum member, because I don't want this to be specific to the type of enum that is used - eventually I want to have several different enums. // This is inside a loop over all the properties on a given object QMetaProperty property = metaObject->property(propertyId); QString propertyName = propertyMeta.name(); QVariant variantValue = propertyMeta.read(serializeObject); // If, internally, this QVariant is of type 'ClefType', // how do I pull out the integer value for this enum? Unfortunately variantValue.toInt(); does not work - custom enums don't seem to be directly 'castable' to an integer value. Thanks in advance, Henry

    Read the article

  • PyQt QAbstractListModel seems to ignore tristate flags

    - by mcieslak
    I've been trying for a couple days to figure out why my QAbstractLisModel won't allow a user to toggle a checkable item in three states. The model returns the Qt.IsTristate and Qt.ItemIsUserCheckable in the flags() method, but when the program runs only Qt.Checked and Qt.Unchecked are toggled on edit. class cboxModel(QtCore.QAbstractListModel): def __init__(self, parent=None): super(cboxModel, self).__init__(parent) self.cboxes = [ ['a',0], ['b',1], ['c',2], ['d',0] ] def rowCount(self,index=QtCore.QModelIndex()): return len(self.cboxes) def data(self,index,role): if not index.isValid: return QtCore.QVariant() myname,mystate = self.cboxes[index.row()] if role == QtCore.Qt.DisplayRole: return QtCore.QVariant(myname) if role == QtCore.Qt.CheckStateRole: if mystate == 0: return QtCore.QVariant(QtCore.Qt.Unchecked) elif mystate == 1: return QtCore.QVariant(QtCore.Qt.PartiallyChecked) elif mystate == 2: return QtCore.QVariant(QtCore.Qt.Checked) return QtCore.QVariant() def setData(self,index,value,role=QtCore.Qt.EditRole): if index.isValid(): self.cboxes[index.row()][1] = value.toInt()[0] self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) print self.cboxes return True return False def flags(self,index): if not index.isValid(): return QtCore.Qt.ItemIsEditable return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsTristate You can test it with this, class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) model = cboxModel(self) self.view = QtGui.QListView() self.view.setModel(model) self.setCentralWidget(self.view) app = QtGui.QApplication(sys.argv) form = MainForm() form.show() app.exec_() and see that only 2 states are available. I'm assuming there's something simple I'm missing. Any ideas? Thanks!

    Read the article

  • QTreeView incorrectly displays the SpinBox if item is checkable and when using QWindowsStyle

    - by Sharraz
    Hello, I'm having a problem with a QTreeView in my program: The SpinBox used to edit the double value of a checkable item is displayed incorrectly when using the Windows style. Only the up and down buttons of the SpinBox can be seen, but not any value. The following example code is able to reproduce the problem: #include <QtGui> class Model : public QAbstractItemModel { public: Model() : checked(false), number(0) {} Qt::ItemFlags flags(const QModelIndex & index) const { return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable; } QVariant data(const QModelIndex &index, int role) const { switch (role) { case Qt::DisplayRole: case Qt::EditRole: return QVariant(number); case Qt::CheckStateRole: return QVariant(checked ? Qt::Checked : Qt::Unchecked); } return QVariant(); } QVariant headerData(int section, Qt::Orientation orientation, int role) const { return QVariant(); } int rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : 1; } int columnCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : 1; } bool setData(const QModelIndex &index, const QVariant &value, int role) { switch (role) { case Qt::EditRole: number = value.toDouble(); emit dataChanged(index, index); return true; case Qt::CheckStateRole: checked = value.toInt(); emit dataChanged(index, index); return true; } return false; } QModelIndex index(int row, int column, const QModelIndex &parent) const { if (!row && !column && !parent.isValid()) return createIndex(0, 0); return QModelIndex(); } QModelIndex parent(const QModelIndex &child) const { return QModelIndex(); } private: bool checked; double number; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QApplication::setStyle(new QWindowsStyle()); QTreeView tree; tree.setModel(new Model()); tree.show(); return app.exec(); } The problems seems to have something to do with the checkbox. If Qt::ItemIsUserCheckable is removed, the SpinBox will be displayed correctly. If the number is replaced by a longer one like 0.01, it can be seen partially. Any idea how this problem can be solved? Do I use the checkbox correctly? Greets, Sharraz

    Read the article

  • Save QList<int> to QSettings

    - by Tobias
    Hello, I want to save a QList<int> to my QSettings without looping through it. I know that I could use writeArray() and a loop to save all items or to write the QList to a QByteArray and save this but then it is not human readable in my INI file.. Currently I am using the following to transform my QList<int> to QList<QVariant>: QList<QVariant> variantList; //Temp is the QList<int> for (int i = 0; i < temp.size(); i++) variantList.append(temp.at(i)); And to save this QList<Variant> to my Settings I use the following code: QVariant list; list.setValue(variantList); //saveSession is my QSettings object saveSession.setValue("MyList", list); The QList is correctly saved to my INI file as I can see (comma seperated list of my ints) But the function crashes on exit. I already tried to use a pointer to my QSettings object instead but then it crashes on deleting the pointer ..

    Read the article

  • Segmentation fault while switching QCompleter for QLineEdit [on hold]

    - by san
    I have a QLineEdit that uses autocompletion one which on focusIn event in which it shows paths from XML List(here I have used hardcoded list) but if user doesn't find the path from that list popped by QCompleter than I want user to be able to browse to path typing '/' in QLineEdit , I am not able to select the paths say /Users etc and on trying to type Segmentation fault occurs. from PyQt4.Qt import Qt, QObject,QLineEdit from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT from PyQt4 import QtGui, QtCore import sys class DirLineEdit(QLineEdit, QtCore.QObject): """docstring for DirLineEdit""" def __init__(self): super(DirLineEdit, self).__init__() self.defaultList = ['~/Development/python/searchMethod', '~/Development/Nuke_python', '~/Development/python/openexr', '~/Development/python/cpp2python'] self.textChanged.connect(self.__dirCompleter) def focusInEvent(self, event): if len(self.text()) == 0: self._pathsList() QtGui.QLineEdit.focusInEvent(self, event) self.completer().complete() def __dirCompleter(self): if len(self.text()) == 0: model = MyListModel(self.defaultList, self) completer = QtGui.QCompleter(model, self) completer.setModel(model) else: dirModel = QtGui.QFileSystemModel() dirModel.setRootPath(QtCore.QDir.currentPath()) dirModel.setFilter(QtCore.QDir.AllDirs | QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files) dirModel.setNameFilterDisables(0) completer = QtGui.QCompleter(dirModel, self) completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) completer.setModel(dirModel) self.setCompleter(completer) def _pathsList(self): completerList = QtCore.QStringList() for i in self.defaultList: completerList.append(QtCore.QString(i)) lineEditCompleter = QtGui.QCompleter(completerList) lineEditCompleter.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion) self.setCompleter(lineEditCompleter) class MyListModel(QtCore.QAbstractListModel): def __init__(self, datain, parent=None, *args): """ datain: a list where each item is a row """ QtCore.QAbstractTableModel.__init__(self, parent, *args) self.listdata = datain def rowCount(self, parent=QtCore.QModelIndex()): return len(self.listdata) def data(self, index, role): if index.isValid() and role == QtCore.Qt.DisplayRole: return QtCore.QVariant(self.listdata[index.row()]) else: return QtCore.QVariant() app = QtGui.QApplication(sys.argv) smObj = DirLineEdit() smObj.show() app.exec_() Please help fix this or suggest better way of implementation?

    Read the article

  • QTreeView memory consumption

    - by Eye of Hell
    Hello. I'm testing QTreeView functionality right now, and i was amazed by one thing. It seems that QTreeView memory consumption depends on items count O_O. This is highly unusual, since model-view containers of such type only keeps track for items being displayed, and rest of items are in the model. I have written a following code with a simple model that holds no data and just reports that it has 10 millions items. With MFC, Windows API or .NET tree / list with such model will take no memory, since it will display only 10-20 visible elements and will request model for more upon scrolling / expanding items. But with Qt, such simple model results in ~300Mb memory consumtion. Increasing number of items will increase memory consumption. Maybe anyone can hint me what i'm doing wrong? :) #include <QtGui/QApplication> #include <QTreeView> #include <QAbstractItemModel> class CModel : public QAbstractItemModel { public: QModelIndex index ( int i_nRow, int i_nCol, const QModelIndex& i_oParent = QModelIndex() ) const { return createIndex( i_nRow, i_nCol, 0 ); } public: QModelIndex parent ( const QModelIndex& i_oInex ) const { return QModelIndex(); } public: int rowCount ( const QModelIndex& i_oParent = QModelIndex() ) const { return i_oParent.isValid() ? 0 : 1000 * 1000 * 10; } public: int columnCount ( const QModelIndex& i_oParent = QModelIndex() ) const { return 1; } public: QVariant data ( const QModelIndex& i_oIndex, int i_nRole = Qt::DisplayRole ) const { return Qt::DisplayRole == i_nRole ? QVariant( "1" ) : QVariant(); } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QTreeView oWnd; CModel oModel; oWnd.setUniformRowHeights( true ); oWnd.setModel( & oModel ); oWnd.show(); return a.exec(); }

    Read the article

  • PyQt4 and QTableView with spinbox and checkbox

    - by ekapek
    Hi, I have a QTableView with QSqlTableModel and with 3 columns, now I need to have: - second column: spinbox after clicked to edit - third column: checkbox (displayed center) My code: class SpinBoxDelegate(QtGui.QItemDelegate): def createEditor(self, parent, option, index): editor = QtGui.QSpinBox(parent) editor.setMinimum(0) editor.setMaximum(100) print 'spinbox' return editor def setEditorData(self, spinBox, index): value = index.model().data(index, QtCore.Qt.EditRole).toInt()[0] spinBox.setValue(value) def setModelData(self, spinBox, model, index): spinBox.interpretText() value = spinBox.value() model.setData(index, value, QtCore.Qt.EditRole) def updateEditorGeometry(self, editor, option, index): editor.setGeometry(option.rect) class myQSqlTableModel(QtSql.QSqlTableModel): def flags(self,index): result = QtSql.QSqlTableModel.flags(self,index); if index.column() == 2: result |= QtCore.Qt.ItemIsUserCheckable return result def data(self,index,role): if not index.isValid: return QtCore.QVariant() value = QtSql.QSqlTableModel.data(self, index, role) if index.column() == 2: if role == QtCore.Qt.CheckStateRole: return QtCore.Qt.Unchecked if QtSql.QSqlTableModel.data(self, index).toInt()[0] else QtCore.Qt.Checked elif role == QtCore.Qt.DisplayRole: return QtCore.QVariant() return value and self.model = myQSqlTableModel(self) self.model.setTable("person") self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.model.select(): self.model.setHeaderData(0, QtCore.Qt.Horizontal, self.tr("ID")) self.model.setHeaderData(1, QtCore.Qt.Horizontal, self.tr("A")) self.model.setHeaderData(2, QtCore.Qt.Horizontal, self.tr("B")) self.view = QtGui.QTableView() self.view.setModel(self.model) self.view.setSortingEnabled(True) spinDelegate = SpinBoxDelegate() self.view.setItemDelegateForColumn(1,spinDelegate) but it does't work: spinbox don't show after click and checkbox can't be clicked and is aligned to left Any help?

    Read the article

  • How do I add a header with data to a QTableWidget in Qt?

    - by San Jacinto
    Hi, I'm still learning Qt and I am indebted to the SO community for providing me with great, very timely answers to my Qt questions. Thank you. I'm quite confused on the idea of adding a header to a QTableWidget. What I'd like to do is have a table that contains information about team members. Each row for a member should contain his first and last name, each in its own cell, an email address in one cell, and office in the other cell. I'd to have a header above these columns to name them as appropriate. I'm trying to start off easy and get just the header to display "Last" (as in last name). Here is my code. int column = m_ui-teamTableWidget-columnCount(); m_ui-teamTableWidget-setColumnCount(column+1); QString* qq = new QString("Last"); m_ui-teamTableWidget-horizontalHeader()-model()-setHeaderData(0, Qt::Horizontal, QVariant(QVariant::String, &qq)); My table gets rendered corretly, but the header doesn't contain what I would expect. It contains 1 cell that contains the text "1". I am obviously doing something very silly here that is wrong, but i am lost. I keep pouring over the documentation, finding nothing. Here are the documentation links to the function calls I am making for the very last line. http://doc.trolltech.com/4.5/qtableview.html#horizontalHeader http://doc.trolltech.com/4.5/qabstractitemview.html#model http://doc.trolltech.com/4.5/qabstractitemmodel.html#setHeaderData Thanks for any and all help. Edit: HOW I SOLVED THE PROBLEM Using some help from the accepted answer, I came up with the following code: m_ui-teamTableWidget-setColumnCount(m_ui-teamTableWidget-columnCount()+1); QTableWidgetItem* qtwi = new QTableWidgetItem(QString("Last"),QTableWidgetItem::Type); m_ui-teamTableWidget-setHorizontalHeaderItem(0,qtwi);

    Read the article

  • How to make item view render rich (html) text in PyQt?

    - by Giorgio Gelardi
    I'm trying to translate code from this thread in python: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * __data__ = [ "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ] def get_html_box(text): return '''<table border="0" width="100%"><tr width="100%" valign="top"> <td width="1%"><img src="softwarecenter.png"/></td> <td><table border="0" width="100%" height="100%"> <tr><td><b><a href="http://www.google.com">titolo</a></b></td></tr> <tr><td>{0}</td></tr><tr><td align="right">88/88/8888, 88:88</td></tr> </table></td></tr></table>'''.format(text) class HTMLDelegate(QStyledItemDelegate): def paint(self, painter, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) painter.save() ctx = QAbstractTextDocumentLayout.PaintContext() ctx.clip = QRectF(0, option.rect.top(), option.rect.width(), option.rect.height()) dl = doc.documentLayout() dl.draw(painter, ctx) painter.restore() def sizeHint(self, option, index): model = index.model() record = model.listdata[index.row()] doc = QTextDocument(self) doc.setHtml(get_html_box(record)) doc.setTextWidth(option.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) class MyListModel(QAbstractListModel): def __init__(self, parent=None, *args): super(MyListModel, self).__init__(parent, *args) self.listdata = __data__ def rowCount(self, parent=QModelIndex()): return len(self.listdata) def data(self, index, role=Qt.DisplayRole): return index.isValid() and QVariant(self.listdata[index.row()]) or QVariant() class MyWindow(QWidget): def __init__(self, *args): super(MyWindow, self).__init__(*args) # listview self.lv = QListView() self.lv.setModel(MyListModel(self)) self.lv.setItemDelegate(HTMLDelegate(self)) self.lv.setResizeMode(QListView.Adjust) # layout layout = QVBoxLayout() layout.addWidget(self.lv) self.setLayout(layout) if __name__ == "__main__": app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) Element's size and position are not calculated correctly I guess, perhaps because I haven't understand at all the style related parts from original code. Can someone help me?

    Read the article

  • how to change headers data

    - by Moayyad Yaghi
    hello i have the following class class AssetTableModel(QtCore.QAbstractTableModel): def init(self,filename=''): super(AssetTableModel,self).init() self.fileName=filename self.dirty = False self.assets = [] self.setHeaderData(0,QtCore.Qt.Horizontal,QtCore.QVariant('moayyad'),QtCore.Qt.EditRole) and i need to change the headers of the columns or the rows ,i used ( self.setHeaderdata()) but its not working ,i have a table that consistes of 2 columns and 2 rows only. is there any other function that changes headers ??. please help thanx in adnvance

    Read the article

  • c++ property class structure

    - by Without me Its just Aweso
    I have a c++ project being developed in QT. The problem I'm running in to is I am wanting to have a single base class that all my property classes inherit from so that I can store them all together. Right now I have: class AbstractProperty { public: AbstractProperty(QString propertyName); virtual QString toString() const = 0; virtual QString getName() = 0; virtual void fromString(QString str) = 0; virtual int toInteger() = 0; virtual bool operator==(const AbstractProperty &rightHand) = 0; virtual bool operator!=(const AbstractProperty &rightHand) = 0; virtual bool operator<(const AbstractProperty &rightHand) = 0; virtual bool operator>(const AbstractProperty &rightHand) = 0; virtual bool operator>=(const AbstractProperty &rightHand) = 0; virtual bool operator<=(const AbstractProperty &rightHand) = 0; protected: QString name; }; then I am implementing classes such as PropertyFloat and PropertyString and providing implementation for the comparator operators based on the assumption that only strings are being compared with strings and so on. However the problem with this is there would be no compiletime error thrown if i did if(propertyfloat a < propertystring b) however my implementation of the operators for each derived class relies on them both being the same derived class. So my problem is I cant figure out how to implement a property structure so that I can have them all inherit from some base type but code like what I have above would throw a compile time error. Any ideas on how this can be done? For those familiar with QT I tried using also a implementation with QVariant however QVariant doesn't have operators < and defined in itself only in some of its derived classes so it didn't work out. What my end goal is, is to be able to generically refer to properties. I have an element class that holds a hashmap of properties with string 'name' as key and the AbstractProperty as value. I want to be able to generically operate on the properties. i.e. if I want to get the max and min values of a property given its string name I have methods that are completely generic that will pull out the associated AbstactProperty from each element and find the max/min no matter what the type is. so properties although initially declared as PropertyFloat/PropertyString they will be held generically.

    Read the article

  • Persistence classes in Qt

    - by zarzych
    Hi, I'm porting a medium-sized CRUD application from .Net to Qt and I'm looking for a pattern for creating persistence classes. In .Net I usually created abstract persistence class with basic methods (insert, update, delete, select) for example: public class DAOBase<T> { public T GetByPrimaryKey(object primaryKey) {...} public void DeleteByPrimaryKey(object primaryKey) {...} public List<T> GetByField(string fieldName, object value) {...} public void Insert(T dto) {...} public void Update(T dto) {...} } Then, I subclassed it for specific tables/DTOs and added attributes for DB table layout: [DBTable("note", "note_id", NpgsqlTypes.NpgsqlDbType.Integer)] [DbField("note_id", NpgsqlTypes.NpgsqlDbType.Integer, "NoteId")] [DbField("client_id", NpgsqlTypes.NpgsqlDbType.Integer, "ClientId")] [DbField("title", NpgsqlTypes.NpgsqlDbType.Text, "Title", "")] [DbField("body", NpgsqlTypes.NpgsqlDbType.Text, "Body", "")] [DbField("date_added", NpgsqlTypes.NpgsqlDbType.Date, "DateAdded")] class NoteDAO : DAOBase<NoteDTO> { } Thanks to .Net reflection system I was able to achieve heavy code reuse and easy creation of new ORMs. The simplest way to do this kind of stuff in Qt seems to be using model classes from QtSql module. Unfortunately, in my case they provide too abstract an interface. I need at least transactions support and control over individual commits which QSqlTableModel doesn't provide. Could you give me some hints about solving this problem using Qt or point me to some reference materials? Update: Based on Harald's clues I've implemented a solution that is quite similar to the .Net classes above. Now I have two classes. UniversalDAO that inherits QObject and deals with QObject DTOs using metatype system: class UniversalDAO : public QObject { Q_OBJECT public: UniversalDAO(QSqlDatabase dataBase, QObject *parent = 0); virtual ~UniversalDAO(); void insert(const QObject &dto); void update(const QObject &dto); void remove(const QObject &dto); void getByPrimaryKey(QObject &dto, const QVariant &key); }; And a generic SpecializedDAO that casts data obtained from UniversalDAO to appropriate type: template<class DTO> class SpecializedDAO { public: SpecializedDAO(UniversalDAO *universalDao) virtual ~SpecializedDAO() {} DTO defaultDto() const { return DTO; } void insert(DTO dto) { dao->insert(dto); } void update(DTO dto) { dao->update(dto); } void remove(DTO dto) { dao->remove(dto); } DTO getByPrimaryKey(const QVariant &key); }; Using the above, I declare the concrete DAO class as following: class ClientDAO : public QObject, public SpecializedDAO<ClientDTO> { Q_OBJECT public: ClientDAO(UniversalDAO *dao, QObject *parent = 0) : QObject(parent), SpecializedDAO<ClientDTO>(dao) {} }; From within ClientDAO I have to set some database information for UniversalDAO. That's where my implementation gets ugly because I do it like this: QMap<QString, QString> fieldMapper; fieldMapper["client_id"] = "clientId"; fieldMapper["name"] = "firstName"; /* ...all column <-> field pairs in here... */ dao->setFieldMapper(fieldMapper); dao->setTable("client"); dao->setPrimaryKey("client_id"); I do it in constructor so it's not visible at a first glance for someone browsing through the header. In .Net version it was easy to spot and understand. Do you have some ideas how I could make it better?

    Read the article

  • Architecture for Qt SIGNAL with subclass-specific, templated argument type

    - by Barry Wark
    I am developing a scientific data acquisition application using Qt. Since I'm not a deep expert in Qt, I'd like some architecture advise from the community on the following problem: The application supports several hardware acquisition interfaces but I would like to provide an common API on top of those interfaces. Each interface has a sample data type and a units for its data. So I'm representing a vector of samples from each device as a std::vector of Boost.Units quantities (i.e. std::vector<boost::units::quantity<unit,sample_type> >). I'd like to use a multi-cast style architecture, where each data source broadcasts newly received data to 1 or more interested parties. Qt's Signal/Slot mechanism is an obvious fit for this style. So, I'd like each data source to emit a signal like typedef std::vector<boost::units::quantity<unit,sample_type> > SampleVector signals: void samplesAcquired(SampleVector sampleVector); for the unit and sample_type appropriate for that device. Since tempalted QObject subclasses aren't supported by the meta-object compiler, there doesn't seem to be a way to have a (tempalted) base class for all data sources which defines the samplesAcquired Signal. In other words, the following won't work: template<T,U> //sample type and units class DataSource : public QObject { Q_OBJECT ... public: typedef std::vector<boost::units::quantity<U,T> > SampleVector signals: void samplesAcquired(SampleVector sampleVector); }; The best option I've been able to come up with is a two-layered approach: template<T,U> //sample type and units class IAcquiredSamples { public: typedef std::vector<boost::units::quantity<U,T> > SampleVector virtual shared_ptr<SampleVector> acquiredData(TimeStamp ts, unsigned long nsamples); }; class DataSource : public QObject { ... signals: void samplesAcquired(TimeStamp ts, unsigned long nsamples); }; The samplesAcquired signal now gives a timestamp and number of samples for the acquisition and clients must use the IAcquiredSamples API to retrieve those samples. Obviously data sources must subclass both DataSource and IAcquiredSamples. The disadvantage of this approach appears to be a loss of simplicity in the API... it would be much nicer if clients could get the acquired samples in the Slot connected. Being able to use Qt's queued connections would also make threading issues easier instead of having to manage them in the acquiredData method within each subclass. One other possibility, is to use a QVariant argument. This necessarily puts the onus on subclass to register their particular sample vector type with Q_REGISTER_METATYPE/qRegisterMetaType. Not really a big deal. Clients of the base class however, will have no way of knowing what type the QVariant value type is, unless a tag struct is also passed with the signal. I consider this solution at least as convoluted as the one above, as it forces clients of the abstract base class API to deal with some of the gnarlier aspects of type system. So, is there a way to achieve the templated signal parameter? Is there a better architecture than the one I've proposed?

    Read the article

  • Memory leak returning QIcon

    - by Stefano
    I started using Qt but I'm facing a big problem: I implemented my custom model that inhrerits from the QAbstractListModel class. What I want to do is to display a list with icon. All works and the image is shown with my code but it creates a memory leak. If I don't return the icon no memory leak is detected. class MyModel : public QAbstractListModel { public: ... private: QIcon myicon; } QVariant MyModel::data(const QModelIndex &index, int role) const { ... if (role == Qt::DecorationRole) { return this->myicon; } ... }

    Read the article

  • QtScript: Passing an array of objects to C++

    - by Plow
    Hi, I want to pass an array of objects from my QtScript to C++ but I have not been able to figure out how to achieve this. As soon as I create an array, the elements inside it are converted to strings before I can access them. This is what I have been trying so far: class myObject : public QObject, public QScriptable { Q_OBJECT public Q_SLOTS: void test(QVariantList list); }; void myObject::test(QVariantList list) { for (QVariantList::const_iterator it = list.begin(); it != list.end(); ++it) { QVariant element = *it; qDebug() << "List element type: " << element.typeName(); if (element.canConvert<QVariantMap>()) { // Not getting here } } } The following script myObject.test([{"foo": 1, "bar": 2}, {"baaz": 3, "baaaz": 4}]); prints List element type: "QString" List element type: "QString" I am using Qt 4.6...

    Read the article

  • How to set QNetworkReply properties to get correct NCBI pages?

    - by Claire Huang
    I try to get this following url using the downloadURL function: http://www.ncbi.nlm.nih.gov/nuccore/27884304 But the data is not as what we can see through the browser. Now I know it's because that I need to give the correct information such as browser, how can I know what kind of information I need to set, and how can I set it? (By setHeader function??) In VC++, we can use CInternetSession and CHttpConnection Object to get the correct information without setting any other detail information, is there any similar way in Qt or other cross-platform C++ network lib?? (Yes, I need the the cross-platform property.) QNetworkReply::NetworkError downloadURL(const QUrl &url, QByteArray &data) { QNetworkAccessManager manager; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader ,"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)"); QNetworkReply *reply = manager.get(request); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QVariant statusCodeV = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); QUrl redirectTo = statusCodeV.toUrl(); if (!redirectTo.isEmpty()) { if (redirectTo.host().isEmpty()) { const QByteArray newaddr = ("http://"+url.host()+redirectTo.encodedPath()).toAscii(); redirectTo.setEncodedUrl(newaddr); redirectTo.setHost(url.host()); } return (downloadURL(redirectTo, data)); } if (reply->error() != QNetworkReply::NoError) { return reply->error(); } data = reply->readAll(); delete reply; return QNetworkReply::NoError; }

    Read the article

  • How can I set QNetworkReply properties to get correct NCBI pages?

    - by Claire Huang
    I try to get this following url using the downloadURL function: http://www.ncbi.nlm.nih.gov/nuccore/27884304 But the data is not as what we can see through the browser. Now I know it's because that I need to give the correct information such as browser, how can I know what kind of information I need to set, and how can I set it? (By setHeader function??) In VC++, we can use CInternetSession and CHttpConnection Object to get the correct information without setting any other detail information, is there any similar way in Qt or other cross-platform C++ network lib?? (Yes, I need the the cross-platform property.) QNetworkReply::NetworkError downloadURL(const QUrl &url, QByteArray &data) { QNetworkAccessManager manager; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader ,"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)"); QNetworkReply *reply = manager.get(request); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); int direction; QVariant statusCodeV = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); QUrl redirectTo = statusCodeV.toUrl(); if (!redirectTo.isEmpty()) { if (redirectTo.host().isEmpty()) { const QByteArray newaddr = ("http://"+url.host()+redirectTo.encodedPath()).toAscii(); redirectTo.setEncodedUrl(newaddr); redirectTo.setHost(url.host()); } return (downloadURL(redirectTo, data)); } if (reply->error() != QNetworkReply::NoError) { return reply->error(); } data = reply->readAll(); delete reply; return QNetworkReply::NoError; }

    Read the article

  • How do I use QXmlQuery properly? (Qt XQuery/XPath)

    - by Steven Jackson
    I'm using the following code to load in an XML file (actually an NZB): QXmlQuery query; query.bindVariable("path", QVariant(path)); query.setQuery("doc($path)/nzb/file/segments/segment/string()"); if(!query.isValid()) throw QString("Invalid query."); QStringList segments; if(!query.evaluateTo(&segments)) throw QString("Unable to evaluate..."); QString string; foreach(string, segments) qDebug() << "String: " << string; With the following input, it works as expected: <?xml version="1.0" encoding="iso-8859-1" ?> <!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.0//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd"> <nzb> <file> <groups> <group>alt.binaries.cd.image</group> </groups> <segments> <segment>[email protected]</segment> </segments> </file> </nzb> However, with the following input no results are returned. This is how the input should be formatted, with attributes: <?xml version="1.0" encoding="iso-8859-1" ?> <!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.0//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd"> <nzb xmlns="http://www.newzbin.com/DTD/2003/nzb"> <file poster="[email protected]" date="1225385180" subject="ubuntu-8.10-desktop-i386 - ubuntu-8.10-desktop-i386.par2 (1/1)"> <groups> <group>alt.binaries.cd.image</group> </groups> <segments> <segment bytes="66196" number="1">[email protected]</segment> <segment bytes="661967" number="1">[email protected]</segment> </segments> </file> </nzb> Please can someone tell me what I'm doing wrong?

    Read the article

  • breakpoint inside QComboBox subclass not working

    - by yan bellavance
    I have subclassed QComboBox to customize it for special needs. The subclass is used to promote QComboBoxes in a ui file from QtDesigner. Everything works except that when I put a break point in a slot, the program does not stop at the breakpoint. I do however know that it is being called from the result it generates. I checked other slots in my program and they work fine with breakpoints. Doing a clean and rebuild all did not fix it. What could be causing this and is there anything I can do about it? The slot in question is the only one in the subclass and is called "do_indexChanged()". You can find the slot on line 37 of the class header below and the signal-slot connection on line 10 of the class source file. CLASS HEADER: #ifndef WVQCOMBOBOX_H #define WVQCOMBOBOX_H #include <QWidget> #include <QObject> #include <QComboBox> #include <QVariant> class wvQComboBox : public QComboBox { Q_OBJECT //Q_PROPERTY(bool writeEnable READ writeEnable WRITE setWriteEnable) public: explicit wvQComboBox(QWidget *parent = 0); bool writeEnable() { return this->property("writeEnable").toBool(); } void setWriteEnable(const bool & writeEnable){ this->setProperty("writeEnable",writeEnable); } bool newValReady() { return this->property("newValReady").toBool(); } void setNewValReady(const bool & newValReady){ this->setProperty("newValReady",newValReady); } QString getNewVal(); int getNewValIndex(); int oldVal; //comboBox Index before user edit began private slots: void do_indexChanged(){ this->setWriteEnable(true); if(oldVal!=currentIndex()){ this->setNewValReady(true); oldVal=currentIndex(); } } protected: void focusInEvent ( QFocusEvent * event ); //void focusOutEvent ( QFocusEvent * event );//dont need because of currentIndexChanged(int) }; #endif // WVQCOMBOBOX_H #include "wvqcombobox.h" wvQComboBox::wvQComboBox(QWidget *parent) : QComboBox(parent) { this->setWriteEnable(true); this->setNewValReady(false); oldVal=this->currentIndex(); connect(this,SIGNAL(currentIndexChanged(int)),this,SLOT(do_indexChanged())); } void wvQComboBox::focusInEvent ( QFocusEvent * event ) { this->setWriteEnable(false); oldVal=this->currentIndex(); } QString wvQComboBox::getNewVal(){ setNewValReady(false); return this->currentText(); } int wvQComboBox::getNewValIndex(){ setNewValReady(false); return this->currentIndex(); }

    Read the article

  • Segmentation fault in Qt Designer 4.6 with custom widget

    - by chedi
    Hi, I had a segmentation fault when using my new Qt Widget with Qt Designer 4.6. The problem arise when trying to preview the new widget. when using gdb I found that the problem is in qdesigner_internal::WidgetFactory::applyStyleToTopLevel: Program received signal SIGSEGV, Segmentation fault. qdesigner_internal::WidgetFactory::applyStyleToTopLevel (style=0x0, widget=0x1829df0) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/widgetfactory.cpp:777 777 /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/widgetfactory.cpp: No such file or directory. in /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/widgetfactory.cpp (gdb) bt #0 qdesigner_internal::WidgetFactory::applyStyleToTopLevel (style=0x0, widget=0x1829df0) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/widgetfactory.cpp:777 #1 0x00007ffff7475bed in qdesigner_internal::QDesignerFormBuilder::createPreview (fw=, styleName=..., appStyleSheet=..., deviceProfile=, scriptErrors= 0x7fffffffbee0, errorMessage=0x7fffffffc3f0) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/qdesigner_formbuilder.cpp:404 #2 0x00007ffff7476773 in qdesigner_internal::QDesignerFormBuilder::createPreview (fw=0x0, styleName=..., appStyleSheet=..., deviceProfile=..., errorMessage=0x0) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/qdesigner_formbuilder.cpp:439 #3 0x00007ffff7532b27 in qdesigner_internal::PreviewManager::createPreview (this=0x837f20, fw=0x1879200, pc=..., deviceProfileIndex=-1, errorMessage=0x7fffffffc3f0, initialZoom=-1) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/previewmanager.cpp:686 #4 0x00007ffff75343cf in qdesigner_internal::PreviewManager::showPreview (this=0x837f20, fw=0x1879200, pc=..., deviceProfileIndex=-1, errorMessage=0x7fffffffc3f0) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/previewmanager.cpp:760 #5 0x00007ffff753472f in qdesigner_internal::PreviewManager::showPreview (this=0x837f20, fw=0x1879200, style=..., deviceProfileIndex=-1, errorMessage=0x7fffffffc3f0) at /var/tmp/qt-x11-src-4.6.0/tools/designer/src/lib/shared/previewmanager.cpp:659 because a null pointer was passed there: void WidgetFactory::applyStyleToTopLevel(QStyle *style, QWidget *widget) { const QPalette standardPalette = style-standardPalette(); if (widget-style() == style && widget-palette() == standardPalette) return; //.... } I'm new in Qt and this is my first custom widget. does anybody have a clue for solving this. here is my widget code MBICInput::MBICInput(QWidget *parent) : QStackedWidget(parent){ displayPage = new QWidget(); displayPage-setObjectName(QString::fromUtf8("displayPage")); inputLB = new QLabel(displayPage); inputLB-setObjectName(QString::fromUtf8("inputLabel")); inputLB-setCursor(QCursor(Qt::PointingHandCursor)); addWidget(displayPage); EditPage = new QWidget(); EditPage-setProperty("EditInputLine", QVariant(true)); EditPage-setObjectName(QString::fromUtf8("EditPage")); inputInput = new QLineEdit(EditPage); inputInput-setGeometry(QRect(5, 10, 231, 25)); inputInput-setObjectName(QString::fromUtf8("input")); addWidget(EditPage); _animation = new QString(""); _message = new QString("Message"); _validator = new QRegExpValidator(QRegExp("[a-zA-Z]+"), this); } MBICInput::~MBICInput() { } QValidator::State MBICInput::validate(QString &text, int &pos) const{ return _validator-validate(text, pos); } void MBICInput::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); } QSize MBICInput::minimumSizeHint() const{ return QSize(200, 40); } QSize MBICInput::sizeHint() const{ return QSize(200, 40); } void MBICInput::setAnimation(const QString &animation){ *_animation = animation; update(); } QString MBICInput::animation() const{ return *_animation; } void MBICInput::setMessage(const QString &message){ *_message = message; update(); } QString MBICInput::message() const{ return *_message; } void MBICInput::mousePressEvent(QMouseEvent *event){ if(currentIndex()==0){ setCurrentIndex(1); }else{ setCurrentIndex(0); } update(); }

    Read the article

1