Qt, How can I sort QTableWidget column if the cells are widgets - qt

I have a QTableWidget, some columns are filled with text, some with numbers, these columns are fine to sort. But I also have a column with custom widgets, how should I enable sorting for these?
My first thought was of course to overload the '<' method on the QTableWidgetItem, but there are no QTableWidgetItem. So what would be the best way to solve this?

QTableWidget is not ideal for this case, consider using QTableView. Anyway, I will show you how to sort a QProgressBar widget in a QTableWidget.
As you already said, you can overload the <() operator for this case. Let's say you have a QProgressBar in column number 4. You have to overload the <() operator.
You have to subclass QProgressBar and QTableWidgetItem.
class CustomTableWidgetItem : public QProgressBar, public QTableWidgetItem
{
Q_OBJECT
public:
CustomTableWidgetItem( QWidget* parent ) : QProgressBar( parent )
{
}
CustomTableWidgetItem(const QString txt = QString("0"))
:QTableWidgetItem(txt)
{
}
bool operator <(const QTableWidgetItem& other) const
{
if(other.column() == 0 /* numeric cell */) {
return QTableWidgetItem::text().toInt() < other.text().toInt();
}
else if(other.column() == 4 /* progress bar */) {
const QProgressBar *p = dynamic_cast<const QProgressBar *>(&other);
if(p != 0) {
if(this->value() < p->value())
return true;
}
}
return false;
}
};
And then you can insert your QProgressBar like this in cell number 4.
Insert QProgressBar like this
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
CustomTableWidgetItem *pgbar = new CustomTableWidgetItem(this);
ui->tableWidget->setCellWidget(ui->tableWidget->rowCount()-1, 4, pgbar);
ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, 4, pgbar);
Let's say you want to have simple text at cell 1 use QTableWidgetItem.
ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, 1, new QTableWidgetItem("Hello"));
If you want to sort numbers as well, for example in cell 0 use CustomTableWidgetItem, since we have implemented an if-statement as you can see above for sorting numbers and progressbar.
ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, 0, new CustomTableWidgetItem(QString::number(ui->tableWidget->rowCount())));
You can use this approach with other widgets as well, just subclass the correct widget, but in general it's better to use QTableView (MVC approach).
Here is a screenshot with QTableWidget and QProgressBar sorting.

Related

Last empty column to fill QTableView

In a QTableView I need the last (rightmost) column to be empty, expandable but not movable. The goal is that the table not to suddenly end (for I use alternate color for rows) or to ugly expand to the right. In QHeaderView there is a setFirstSectionMovable(bool); I need something similar for the last section, letting the rest of them movable. (in other words: Fill the rest of the table with an empty not movable column). Any clue how to acheive this?
I did override mousePressEvent() in a subclass of QHeaderView to skip the last section but it still can be moved by moving other column in its place and I don't know how to prevent this.
AMOQ:
Be HeaderView a subclass of QHeaderView and have
setSectionsMovable(true);
setStretchLastSection(true);
Treat the sectionMoved signal:
connect(this, &QHeaderView::sectionMoved, [this](int, int, int newVisual) {
if(newVisual == count()-1) { moveSection(newVisual, newVisual-1); }
});
Override mousePressEvent:
void HeaderView::mousePressEvent(QMouseEvent* event) {
int logicalIdx = logicalIndexAt(event->pos());
if(logicalIdx != count()-1) { QHeaderView::mousePressEvent(event); }
}

Shared layout by widgets in QStackedWidget

I have a QStackedWidget with QWidgets. My QWidgets differ a bit, one has an additional button, other lacks a combo box and so on but all of them can be arranged in the same QGridLayout.
And that is exactly what I would like to achieve. I would like to have a QGridLayout in my QStackedWidget that is shared by all my QWidgets. Additionally my main window (QDockWidget) can be resized and I would like to set different column and row stretch for the grid layout.
Is there a clean solution for this?
I came up with two ideas.
One is to have a QGridLayout in each QWidget and connect them all together so that when one is resized, others do the same. However, the more QWidgets I had, the more complicated it would have been.
My second idea is to have one QGridLayout with QStackedWidget in each cell. The bigger the QGridLayout was, the harder it would be to maintain it.
None of my ideas seem to be good.
I am using PyQt4 but examples in C++ are welcome as well.
This doesn't seem to warrant anything more than maybe a shared addWidgetsToGridLayout function that can be used for each widget in the stack, which is a different object because it shows different things. Sharing widgets is bad in this setup, so make sure each widget in the stack has its own distinct widgets.
I don't understand why you would want to resize invisible widgets on resize. When you switch to another widget on the stack, Qt will make sure the proper events are called to properly resize the layout.
A layout cannot be shared. The layout system was not designed for it.
You could have a setup function that creates widgets in a layout, and returns the layout. The layout carries the widgets. You can then apply that layout to a widget, establishing the contents that way. The setup function can take parameters that customize its behavior. For example:
enum WidgetType {
Normal, WithButton, WithCombo
};
QGridLayout* setup(WidgetType type) {
auto l = new QGridLayout;
l.addWidget(0, 0, new QLabel("Hello"));
l.addWidget(0, 1, new QLabel("World"));
switch (type) {
case WithButton:
l.addWidget(1, 0, new QPushButton("Click Me!"));
break;
case WithCombo:
if (auto combo = new QComboBox) {
...
l.addWidget(1, 1, combo);
}
break;
case Normal:
break;
}
return l;
};
void test() {
QWidget w1, w2;
w1.setLayout(setup(Normal));
w2.setLayout(setup(WithButton));
}
Of course, presumably you'll want to easily refer to the widgets. Thus it's best that you create a custom widget that can take multple forms, and holds the widget by value or by pointer as needed:
class Widget : public QWidget {
QGridLayout m_layout{this};
QLabel m_label1("Hello");
QLabel m_label2("World");
QPointer<QPushButton> m_button;
QPointer<QComboBox> m_combo;
public:
Widget(WidgetType type, QWidget *parent = nullptr) : QWidget(parent) {
m_layout.addWidget(0, 0, &m_label1);
m_layout.addWidget(0, 1, &m_label2);
switch (type) {
case WithButton:
m_button = new QPushButton("Click Me!");
m_layout.addWidget(1, 0, m_button.data());
break;
case WithCombo:
m_combo = new QComboBox;
...
m_layout.addWidget(1, 1, m_combo.data());
break;
case Normal:
break;
}
}
};

Hide QLineEdit blinking cursor

I am working on QT v5.2
I need to hide the blinking cursor (caret) of QLineEdit permanently.
But at the same time, I want the QLineEdit to be editable (so readOnly and/or setting editable false is not an option for me).
I am already changing the Background color of the QLineEdit when it is in focus, so I will know which QLineEdit widget is getting edited.
For my requirement, cursor (the blinking text cursor) display should not be there.
I have tried styleSheets, but I can't get the cursor hidden ( {color:transparent; text-shadow:0px 0px 0px black;} )
Can someone please let me know how can I achieve this?
There is no standard way to do that, but you can use setReadOnly method which hides the cursor. When you call this method it disables processing of keys so you'll need to force it.
Inherit from QLineEdit and reimplement keyPressEvent.
LineEdit::LineEdit(QWidget* parent)
: QLineEdit(parent)
{
setReadOnly(true);
}
void LineEdit::keyPressEvent(QKeyEvent* e)
{
setReadOnly(false);
__super::keyPressEvent(e);
setReadOnly(true);
}
As a workaround you can create a single line QTextEdit and set the width of the cursor to zero by setCursorWidth.
For a single line QTextEdit you should subclass QTextEdit and do the following:
Disable word wrap.
Disable the scroll bars (AlwaysOff).
setTabChangesFocus(true).
Set the sizePolicy to (QSizePolicy::Expanding, QSizePolicy::Fixed)
Reimplement keyPressEvent() to ignore the event when Enter/Return is hit
Reimplement sizeHint to return size depending on the font.
The implementation is :
#include <QTextEdit>
#include <QKeyEvent>
#include <QStyleOption>
#include <QApplication>
class TextEdit : public QTextEdit
{
public:
TextEdit()
{
setTabChangesFocus(true);
setWordWrapMode(QTextOption::NoWrap);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setFixedHeight(sizeHint().height());
}
void keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
event->ignore();
else
QTextEdit::keyPressEvent(event);
}
QSize sizeHint() const
{
QFontMetrics fm(font());
int h = qMax(fm.height(), 14) + 4;
int w = fm.width(QLatin1Char('x')) * 17 + 4;
QStyleOptionFrameV2 opt;
opt.initFrom(this);
return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
expandedTo(QApplication::globalStrut()), this));
}
};
Now you can create an instance of TextEdit and set the cursor width to zero :
textEdit->setCursorWidth(0);
Most straight forward thing I found was stolen from this github repo:
https://github.com/igogo/qt5noblink/blob/master/qt5noblink.cpp
Basically you just want to disable the internal "blink timer" Qt thinks is somehow good UX (hint blinking cursors never were good UX and never will be - maybe try color or highlighting there eh design peeps).
So the code is pretty simple:
from PyQt5 import QtGui
app = QtGui.QApplication.instance()
app.setCursorFlashTime(0)
voilĂ .
Solution in python:
# somelibraries
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.setFocus() # this is what you need!!!
container = QWidget()
container.setLayout(self.layout)
# Set the central widget of the Window.
self.setCentralWidget(container)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
I ran into the same problem but setReadOnly is not a viable option because it alters the UI behavior in other places too.
Somewhere in a Qt-forum I found the following solution that actually solves the problem exactly where it occurs without having impact on other parts.
In the first step you need to derive from QProxyStyle and overwrite the pixelMetric member function:
class CustomLineEditProxyStyle : public QProxyStyle
{
public:
virtual int pixelMetric(PixelMetric metric, const QStyleOption* option = 0, const QWidget* widget = 0) const
{
if (metric == QStyle::PM_TextCursorWidth)
return 0;
return QProxyStyle::pixelMetric(metric, option, widget);
}
};
The custom function simply handles QStyle::PM_TextCursorWidth and forwards otherwise.
In your custom LineEdit class constructor you can then use the new Style like this:
m_pCustomLineEditStyle = new CustomLineEditProxyStyle();
setStyle(m_pCustomLineEditStyle);
And don't forget to delete it in the destructor since the ownership of the style is not transferred (see documentation). You can, of course, hand the style form outside to your LineEdit instance if you wish.
Don't get complicated:
In QtDesigner ,
1.Go the the lineEdit 's property tab
2.Change focusPolicy to ClickFocus
That's it...

Can you set a QWidget to take up an entire column of a QTreeWidget?

I have a custom QTreeWidget subclass that I'm using to display track names/etc. in my MIDI editor project (https://github.com/waddlesplash/ragingmidi). I'd like to add another column to this tree widget, but with one widget taking up the whole column and not per-item widgets.
Is this possible or will I have to figure out some other solution?
EDIT: I'm trying to accomplish something like this: http://www.anvilstudio.com/compose.jpg - see the last "column" in the header view (3rd after "L/R Balance") showing all the lines/notes (which is entirely custom, and written in VB.NET and closed-source anyway).
EDIT 2: You can't see it, but the last column scrolls without the other columns scrolling in the above picture. In their method, you have to scroll using the mouse. I want a scrollbar.
Looking at the Qt documentation, there seems to be a few options to accomplish this, however there are a few important factors to address before you can decide what approach best suits your needs.
Is the content being displayed in this custom tree column static or dynamic?
Is there a one to one mapping of rows from your QTreeWidget to your custom tree column?
If your custom tree column content IS static and there IS a one to one mapping of rows , use of the QTreeWidget::setItemWidget ( QTreeWidgetItem * item, int column, QWidget * widget ) function should suffice.
However, if the content of your custom tree column is dynamic OR there is not a one to one mapping of rows, this will require a more complex approach.
As described in the documentation for QTreeWidget; "If you want to display custom dynamic content or implement a custom editor widget, use QTreeView and subclass QItemDelegate. "
QItemDelegate, and its sub classes, perform all drawing facilities for items inserted into Qt item views (like QTreeView, QListView, QTableView, etc..). This essentially allows you to control ALL drawing operations for any item inserted into a QTreeView class, letting you draw dynamic content in addition to being able to extend content across multiple rows.
Having implemented a similar approach for a QListWidget, I recommend using QStyledItemDelegate in lieu of QItemDelegate as it allows you to more easily integrate this widget with your application's style layout. As you did not detail the exact use of this custom QWidget, you also might need the additional facilities provided by QItemEditorCreator, QItemEditorCreatorBase and QItemEditorFactory. I would post the similar widget I developed here if I could, but sadly it is part of a proprietary software suite.
This is not completely pretty, because it got it's problems when the custom widget is in the right-most column and the column is made narrow, but it's a start:
#include <QtGui>
class TreeWidget : public QTreeWidget
{
Q_OBJECT
public:
TreeWidget();
QRect columnRect(int column) const;
private slots:
void repositionColumnWidget();
private:
QPushButton * mColumnWidget;
};
TreeWidget::TreeWidget()
: mColumnWidget(new QPushButton("Custom Column Button", viewport()))
{
const int COLUMN_COUNT = 6;
setColumnCount(COLUMN_COUNT);
for (int row = 0; row < 400; ++row)
{
QStringList columns;
for (int column = 0; column < COLUMN_COUNT; ++column)
{
columns << QString("row %1, column %2").arg(row + 1).arg(column + 1);
}
addTopLevelItem(new QTreeWidgetItem(columns));
}
for (int column = 0; column < COLUMN_COUNT; ++column)
{
resizeColumnToContents(column);
}
repositionColumnWidget();
mColumnWidget->show();
connect(header(), SIGNAL(sectionResized(int,int,int)), this, SLOT(repositionColumnWidget()));
connect(header(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(repositionColumnWidget()));
connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(repositionColumnWidget()));
connect(horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(repositionColumnWidget()));
}
QRect TreeWidget::columnRect(int column) const
{
int itemCount = topLevelItemCount();
if (!itemCount)
{
return QRect();
}
int columnX = header()->sectionViewportPosition(column);
int columnY = visualItemRect(topLevelItem(0)).top();
int columnWidth = header()->sectionSize(column);
int columnHeight = visualItemRect(topLevelItem(itemCount-1)).bottom() - columnY + 1;
return QRect(columnX, columnY, columnWidth, columnHeight);
}
void TreeWidget::repositionColumnWidget()
{
mColumnWidget->setGeometry(columnRect(3));
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(true);
TreeWidget treeWidget;
treeWidget.resize(800, 600);
treeWidget.show();
return a.exec();
}
#include "main.moc"
The though that has come to my mind after a week is to hijack the H-scrollbar for the QTreeWidget, and then make that scrollbar scroll only the final column. Because right now, all the columns fit when the window is 620x670px, and who has a screen that small anymore?
Unless anyone has a better solution or objections as to why this is a bad idea, this is the way I'm going to do it.

How do I make a QVector of widgets?

How do I make a QVector (or some other container class) of a dynamic number of widgets, such as QPushButton or QComboBox in Qt 4?
I've used the following in my window class's constructor:
QVector<QComboBox*> foo; // Vector of pointers to QComboBox's
And now I want to fill it with some number of controls which can change dynamically:
for(int count = 0; count < getNumControls(); ++count) {
foo[count] = new QComboBox();
}
I've searched for hours trying to find the answer to this. The Qt forums mention making a QPtrList, but that class no longer exists in Qt4.
I'd later try to get the text value from each using array-style indexing or the .at() function.
I would really appreciate an example of declaring, initializing, and populating any data structure of any QWidgets (QComboBox, QPushButton, etc.)
here you go :)
#include <QWidget>
#include <QList>
#include <QLabel>
...
QList< QLabel* > list;
...
list << new QLabel( parent, "label 1" );
..
..
foreach( QLabel* label, list ) {
label->text();
label->setText( "my text" );
}
If you are trying just to get a simple example to work, its important that your widgets have a parent (for context / clean up) purposes.
Hope this helps.
foo[count] = new QComboBox();
This won't affect the size of foo. If there isn't already an item at index count, this will fail.
See push_back, or operator<<, which add an item to the end of the list.
QVector<QComboBox*> foo;
// or QList<QComboBox*> foo;
for(int count = 0; count < getNumControls(); ++count) {
foo.push_back(new QComboBox());
// or foo << (new QComboBox());
}
Later, to retrieve the values:
foreach (QComboBox box, foo)
{
// do something with box here
}

Resources