Menu
  • HOME
  • TAGS

In QTableView/QTableWidget : How to make the alternating rows to fully vertically fill the table?

qt,qtableview,qtablewidget

That's IMHO not possible without subclassing QTableWidget since Qt only colors actual table rows. In your example the table is not entirely filled with rows, so there's no alternating coloring of the whole table.

QTableView output save as .csv or .txt

c++,qt,csv,qt4,qtableview

You may customize it according to your actual needs: // [Collect model data to QString] QString textData; int rows = model->rowCount(); int columns = model->columnCount(); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { textData += model->data(model->index(i,j)).toString(); textData +=...

How to auto stretch QTableView columns and keep them being adjustable

qt,header,pyqt,qtableview

so here is a little trick I came up with. I modified the resize event of MyWindow to resize your QTableWidget. class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) self.tableModel=Model(self) #Set the model as part of your class to access it in the event handler self.view=QTableView(self) self.view.setModel(self.tableModel) #Modified here too self.view.horizontalHeader().setResizeMode(QHeaderView.Interactive)...

How to insert and remove row from model linked to QTableView

python,qt,model,pyqt,qtableview

Mistake was in insertRows() method. The incoming row argument variable (which is selected QModelIndex.row() number) was accidentally re-declared in for loop: for row in range(rows): I've renamed the argument row variable to postion and the fixed working code is posted below (the proxyB sorting attribute was commented out. It displays...

How to display QVector3D in one cell in QTableView via qAbstractTableModel's subclass

c++,qt,qt5,qtableview,qvector3d

The Qt::DisplayRole requires a QString in the variant, but you are providing a QVector3D. There is no conversion from QVector3D to QString in QVariant (see documentation). You should either convert the Vector to a string representation yourself, or use a QStyledItemDelegate to override the displayText method for converting QVector3D to...

QTableView inside QTabWidget does not show data

c++,qt,sqlite,qtableview,qtabwidget

As Greenflow pointed out, problem was in the constructor, in particular in the order of initialization. The constructor is modified as follows AlisnagMainWindow::AlisnagMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), db ( QSqlDatabase::addDatabase("QSQLITE")), loans_model( new QSqlRelationalTableModel(this, db) ), people_model( new QSqlTableModel(this, db) ), items_model( new QSqlRelationalTableModel(this, db) ) { ui->setupUi(this); connect(ui->actionNew, SIGNAL(triggered()),...

QItemDelegate with custom widgets

c++,qt,qtableview,qitemdelegate

You can keep the editor widget as a member of class and emit commitData when the current index of one of the comboboxes has changed. So you can connect currentIndexChanged(int) to a slot and emit commitData from there: QWidget *UserDefinedUnitsDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem & option ,const QModelIndex & index ) const...

Cannot connect (null)::selectionChanged to QTableView

c++,qt,qt-creator,signals-slots,qtableview

The signal slot connection has failed since table->selectionModel() has returned null. If you set the model for your table before making signal slot connection, table->selectionModel() will return a valid model, making the signal slot connection successful....

Word Wrap with HTML? QTabelView and Delegates

c++,qt,delegates,qtableview

Be aware that performance will be terrible. void HTMLDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const { QStyleOptionViewItemV4 options = option; initStyleOption(&options, index); painter->save(); QTextDocument doc; QTextOption textOption(doc.defaultTextOption()); textOption.setWrapMode(QTextOption::WordWrap); doc.setDefaultTextOption(textOption); doc.setHtml(options.text); doc.setTextWidth(options.rect.width()); options.text = "";...

QTableView How to select multiple columns programmatically

c++,qt,multiple-columns,qtableview,qtgui

If you just need to ensure to allow the user to select multiple columns, you need to set up the proper selection mode as follows: tableView->setSelectionMode(QAbstractItemView::MultiSelection); If you would like to do this programatically, this is the way of doing it: QModelIndexList itemSelection = tableView->selectionModel()->selectedColumns(); int currentColumn = itemSelection.first().column(); QItemSelection...

Show image in a column of QTableView from QSqlTableModel

c++,qt,qtableview,qtablewidgetitem

A rough idea is to use QStandardItem::setData to set a QPixmap(transformed into QVariant) on it, then you can set the QStandardItem on the QStandardItemModel. Sequence: QImage--->QPixmap--->QVariant--->QStandardItem--->QStandardItemModel For example: QStandardItemModel *model = new QStandardItemModel; QImage image(":/cat/lovers/own/myCat.jpg"); QStandardItem *item = new QStandardItem(); item->setData(QVariant(QPixmap::fromImage(image)), Qt::DecorationRole); model->setItem(0, 0, item); ui->tableView->setModel(model);...

How to contro QTableView Item's outline

python,qt,pyqt,pyside,qtableview

Qt stylesheets are very mighty for styling and I recommend them. With self.setStyleSheet('QTableView::item{background:black;} QTableView{gridline-color:black;}') instead of setPalette in your example you achieve black items and black grid lines of the table. You can do much more with style sheets, for example change the background of the item when selected. See...

How to select QTableView row with one click

python,qt,model,pyqt,qtableview

You can use setSelectionBehavior function of QTableView to set the selection behavior to QTableView.SelectRows : self.tableview.setSelectionBehavior(QTableView.SelectRows); Now when you click on an item, the entire row is selected....

How to move the focus from a QLineEdit to a QTableView editable cell

qt,qwidget,qtableview,qlineedit,qt5.4

Subclass QLineEdit and override keyPressEvent() to detect when the F5 key is pressed, or install an event filter on the QLineEdit. If you create and show the dialog during the key event processing the dialog will automatically receive a focus in event and the first widget in the dialog that...

Sort QTableView column containing index widgets

c++,qt,c++11,qtableview,qstandarditemmodel

By default, the QStandardItemModel uses whatever the data for the Qt::DisplayRole is to do the sorting. While it's possible to change the role using setSortRole, for index widgets the easiest thing to do is put some sorting hash value into the display role (note: this doesn't affect how the widget...

Save data in database after tableView data changed

c++,database,qt,qtableview

You can use QSqlTableModel to show a table contents in a QTableView : QSqlTableModel * model = new QSqlTableModel(this,db); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->setTable( "someTable" ); model->select(); ui->tableView->setModel( model ); For saving or cancelling changes you can begin a tranaction and commit or rollback at the end. Starting a transaction is like :...

setting QCombobox selected text to specific data column when using QTableView

c++,qt,qtableview,qcombobox

The proper solution was the one pointed out by hank : using QComboBox::setModelColumn. Hank, I am posting this answer because I couldn't find out how to mark your comment as the answer.

How to change QTableView items Orientation from Vertical to Horizontal?

python,qt,model,pyqt,qtableview

An interesting assignment... class Model2(QAbstractTableModel): def __init__(self, model, parent=None): self.model = model QAbstractTableModel.__init__(self, parent) def rowCount(self): return self.model.columnCount() def columnCount(self): return self.model.rowCount() def data(self, a, b): return self.model.data(b, a) ...

QTableView row remove

c++,qt,qtableview,qpushbutton,row-removal

On workaround is to use QObject::setObjectName and set some names to the buttons you add : viewButton.setObjectName(QString("%1").arg(i)); And in button_clicked slot you can retrieve the row number using the object name : void MainWindow::button_clicked() { // by this line I can get the sender of signal QPushButton *pb = qobject_cast<QPushButton...

Understanding MVC in a QAbstractTableModel

model-view-controller,pyqt,qtableview,qabstracttablemodel

As stated in the comment, your model is your list of object. You should subclass QAbstractTableModel to use this list. Here's my code snippet for this: import sys import signal import PyQt4.QtCore as PCore import PyQt4.QtGui as PGui class OneRow(PCore.QObject): def __init__(self): self.column0="text in column 0" self.column1="text in column 1"...

undelete row from QTableView

python-3.x,qtableview,pyqt5,qsqltablemodel

It's weird that nobody here had answered my question... After several tries... Including closing the editor and relaunching it... It appears that to return the row to its previous state - in this case "not marked deleted"- we must use the "revert" method. But the mark "!" does not change...

How to re-arrange QTableView's Columns Order

python,qt,pyqt,qtableview

In case you really want to re-arrange the columns yourself: You can move or swap sections via the moveSection and swapSections methods of the horizontalHeader. headerView.moveSection(x, y) will move column x such that it's column y afterwards, while headerView.swapSections(x,y) will - obviously - swap the positions of the two columns....

How to extend Qt Widgets that do not have model support by default

python,qt,model,pyqt,qtableview

This is what the QDataWidgetMapper class was designed for. The following blog has a great tutorial covering exactly how to implement it: http://www.yasinuludag.com/blog/?p=98 EDIT: I should add that QDataWidgetMapper works with QWidget and its subclasses, so QAction would not apply. For classes that are not QWidget or its subclasses, you...

Can't find error on definition of TextEdit Item Delegate

c++,qt,qtableview,qtgui,qdialog

You seem to be static_cast'ing a QWidget pointer. That is not a good idea. QInputDialog *inputDialog = static_cast<QInputDialog*>(editor); In short, static_cast is meant to be used for situations where you do know that at compilation-time that it is safe to cast from one type to another. However, in this case,...

How to make QTableView to enter the editing mode only on double-click

python,model,pyqt,qtableview

you need to reimplement the even handler keyPressEvent on your QTableView. To do so, you can create a custom QTableView class and reimplement the event handler inside it. from PyQt4.QtCore import * from PyQt4.QtGui import * import sys #Your new customized QTableView class CustomQTableView(QTableView): def __init__(self, *args, **kwargs): QTableView.__init__(self, *args,...

QTableView disconnect all delegates

qt,qtableview

From Qt docs for setItemDelegate(): Any existing delegate will be removed, but not deleted. QAbstractItemView does not take ownership of delegate. What you need to do is for each column delegate that you are customizing, remember (somewhere) the old delegate first and eventually restory it. You also need to delete...

Qt event for delegate in table

qt,qt5,qtableview,qitemdelegate

Mouse events are send to the QAbstractItemDelegate::editorEvent() method, even if they don't start editing of the item. See: http://doc.qt.io/qt-5/qabstractitemdelegate.html#editorEvent...

How to alternate background color of a table view using QSS?

python,qt,pyqt,qtableview,qss

Here is how to control Item's background color using a model. CSS is used later for everything else: import sys, os from PyQt4 import QtCore, QtGui app=QtGui.QApplication(sys.argv) class TableModel(QtCore.QAbstractTableModel): def __init__(self): QtCore.QAbstractTableModel.__init__(self) self.items=['One','Two','Three','Four','Five','Six','Seven'] def rowCount(self, parent=QtCore.QModelIndex()): return len(self.items) def columnCount(self, index=QtCore.QModelIndex()): return 1 def data(self, index, role): if not index.isValid()...

QTableView re-focus the view to specific column

c++,qt,qtableview

Before you do your sort, store the current values for where the scroll bars are with int vPos = yourQTableView->verticalScrollBar()->sliderPosition(); int hPos = yourQTableView->horizontalScrollBar()->sliderPosition(); then after the sort, set it back yourQTableView->verticalScrollBar()->setSliderPosition(vPos); yourQTableView->horizontalScrollBar()->setSliderPosition(hPos); The signals you are looking for are signals of QSortFilterProxyModel inherited from QAbstractItemModel: layoutAboutToBeChanged() layoutChanged() ...

How to prevent QTableView item from getting cleared on double-click

python,qt,model,pyqt,qtableview

You need to sett the return value for data when called with EditRole: def data(self, index, role): if not index.isValid(): return false row=index.row() if row>len(self.items): return false if role == Qt.DisplayRole or role == Qt.EditRole: return self.items[row] ...

Row and Column numbers of selected cells in QTableWidget

python,pyqt,pyqt4,qtableview,qtablewidget

The idea behind this code is to create a custom QTableWidget class that is adding a mouse release event. from PyQt4 import QtCore, QtGui class CustomQTableWidget(QtGui.QTableWidget): def __init__(self, *args, **kwargs): QtGui.QTableWidget.__init__(self, *args, **kwargs) #Fill Qtable self.insertColumn (0) self.insertColumn (1) self.insertColumn (2) self.insertColumn (3) self.insertRow (0) self.insertRow (1) self.insertRow (2) self.insertRow...

Editable checkbox only column in QTableView

c++,qwidget,qtableview,qt5.3,qcheckbox

Replace the flag Qt::ItemIsEditable with the flag Qt::ItemIsEnabled The first one tells Qt to create an editor for the value present in the model, which seems to be a texteditor in your case. If the value is of type bool then a dropdown list containing true and false would be...

How to use QComboBox as delegate with QTableView

python,qt,pyqt,qtableview,qcombobox

Your original code is working in PyQt5, the combobox stays open. But the user has to click to open the editor and then to click to open the combobox. To avoid this i replaced QComboBox by QlistWidget in your code. Additionally i set editorGeometry: import sys # from PyQt4.QtCore import...

Acquire row data from QTableView

c++,qt4,qtableview

Try to connect the QAbstractItemView::clicked(QModelIndex) signal, connect(ui->tableView, SIGNAL(clicked(QModelIndex)),this, SLOT(GetField())); which should return the current item clicked. Once you have the item, in the slot GetField(QModeilIndex index) you can access the selected row with something like: row = index.row() and then you should be able to access your field with field...

Qt delegate setting mouseover state for checkbox

c++,qt,qt4,qtableview,qstyleditemdelegate

After some investigation I found that the issue was that my editorEvent() method needed to return true (indicating that the cell contents have changed) to force the repaint of the cell and thus set the selected state. Code is below: bool CheckBoxDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex&...

QTableView no selection

qt,model-view-controller,selection,qtableview

Okay, I figured it out, and yes, if I posted the code someone would have gotten it but I'm afraid due to the size of the project, it would have probably turned just about anyone anyway. I also didn't know you could turn selecting off in the model (not the...

Use same QTableView in different tabs

python,pyqt,qtableview

I think you might be misinterpreting the function of QTableView; it is meant to be one specific view at a set of data, so exchanging filters when switching tabs is performing worse than having two QTableViews. The elegant solution you're looking for is thus having two independent QTableViews, not one....

Display a large csv file in PyQt Table View

python,csv,pyqt,qtableview,qstandarditemmodel

Most likely you want to just load the parts of file that the user can see (plus a little bit on either side so you can determine when to load more). You should be able to apply the techniques discussed in Big Tables page. There may be other similar tutorials...

How to select QTableView index or row from inside of Model

python,pyqt,qtableview,qabstracttablemodel

You can achieve the selection within the filterAcceptsRow() method of the proxy model, but doing so would require the following: That your proxy model (or source model) contain a reference to the QTableView instance. That your proxy model contain an attribute indicating whether it is active. This is because you...

QTableWidget: don't close editor when pressing Enter

qt,qtableview,qtablewidget,qtablewidgetitem

You should modify the table's item delegate and use event filters to filter out Enter event and implement custom behavior: class MyDelegate : public QStyledItemDelegate { public: MyDelegate(QObject* parent) : QStyledItemDelegate(parent) {} QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const { QWidget* editor = QStyledItemDelegate::createEditor(parent, option, index); editor->installEventFilter(const_cast<MyDelegate*>(this));...

How to control other widgets with an QAbstractTableModel model?

python,qt,model,pyqt,qtableview

The comment by Martin is already a good starting point, but in your custom model you also have to emit a dataChanged signal in the setData method in order for it to work. Then you could also define your own custom signals and emit them and connect for them. However,...

dataChanged signal does not work with ComboBoxDelegate

c++,qt,combobox,qtableview,qstyleditemdelegate

The problem with your delegate implementation is that you do not emit commitData signal when the combo index is changed. It's stated in the Qt documentation : This signal must be emitted when the editor widget has completed editing the data, and wants to write it back into the model....

Changing text direction in QTableView header

qt,qtableview,qtreeview

You can achieve that by providing your own implementation of QHeaderView. Here is an example implementation, which overrides the paintSection method to paint the text vertically. class MyHeaderView(QtWidgets.QHeaderView): def __init__(self, parent=None): super().__init__(Qt.Horizontal, parent) self._font = QtGui.QFont("helvetica", 15) self._metrics = QtGui.QFontMetrics(self._font) self._descent = self._metrics.descent() self._margin = 10 def paintSection(self, painter, rect,...

QTableView: update model on the fly and select correct line

python,model-view-controller,pyqt,qtableview

I managed to do it ! From this post (C++): How to refresh a QSqlTableModel while preserving the selection? The resulting code in python is: def markOneRead(self, element): """Slot to mark an article read""" table = self.liste_tables_in_tabs[self.onglets.currentIndex()] new = table.model().index(element.row(), 12).data() if new == 0: return else: # Save the...